繁体   English   中英

下标值既不是数组也不是指针也不是向量的错误

[英]Error with subscripted value being neither array nor pointer nor vector

    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->border[i][j]); 这会引发错误并停止整个程序的编译。

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

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

尝试这个:

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);

在您可以完美地工作并完全理解它之前,请不要尝试更复杂的事情。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM