【问题标题】:Error with subscripted value being neither array nor pointer nor vector下标值既不是数组也不是指针也不是向量的错误
【发布时间】:2015-08-20 00:47:21
【问题描述】:
    void display_grid(struct game_board *M, FILE *stream) {
        int i, j;

        /* malloc memory for appropriate amount of rows */
        M->border = malloc(sizeof(*M->border) * (M->width + 4));


        for (i = 0; i <= M->width; i+=2){
            M->border[i] = M->border[M->width + 1] = '+';
            for (j = 1; j <= M->width; j+=2){
                M->border[j] = M->border[M->width] = ' ';
                fprintf(stream, "%c\n", M->border[i][j]);
            }
        }
        M->border[M->width + 2] = '\0';

        fflush(stream);
   }

我的问题是关于fprintf(stream, "%c\n", M-&gt;border[i][j]); 这一行,它会发出错误并停止整个程序的编译。

目前,我只是尝试从用户从命令行提供的内容中读取高度和宽度,并使用它打印出 2D 网格,然后我可以稍后使用该网格进行修改等。

我有一个解决方案,我 认为 可能会修复它,但我不知道如何实现它。我相信为了解决问题,我需要将边框分配为 **,然后将行分配为 *

【问题讨论】:

  • 等等...border 有多少个元素?看起来好像你用width+4 构造它,但试着把它读成width(width+1)
  • 好吧,我可能已经解决了一些问题。我最初在程序开始时将边界声明为结构内的 char *。在我的理解中,这反过来意味着我已经声明了一个一维数组。但是通过将边界声明更改为 char **,我现在已将其声明为 2D 数组。这准确吗?
  • 您似乎对数组的工作方式有误解。简短的回答是声明一个指针构造一个数组是非常不同的事情。更长的答案是,我敦促您单独使用数组(即不作为结构或复杂项目的一部分),直到您可以轻松处理 1D 或 2D(或更高),然后将它们合并到其他代码中。
  • char **ano 二维数组!设置和使用比使用适当的 2D 阵列更复杂。我同意@Beta。你真的应该在开始跑步之前先学会走路。
  • struct game_board 的定义是什么?

标签: c arrays pointers


【解决方案1】:

试试这个:

int **A;                        /* A points nowhere in particular */

A = malloc(sizeof(int*) * 3);   /* A points to the head of an array of int* */

A[0] = malloc(sizeof(int) * 4); /* the first element of A points to an array of int */
A[1] = malloc(sizeof(int) * 4);
A[2] = malloc(sizeof(int) * 4);

/* A can now be used as a 3x4 array */

A[2][3] = 99;
printf("%d\n", A[2][3]);

/* don't forget to tidy up */

free(A[0]);
free(A[1]);
free(A[2]);
free(A);

在您完全理解并完全理解之前,不要尝试任何更复杂的事情。

【讨论】:

    猜你喜欢
    • 2013-07-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多