[英]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.