![](/img/trans.png)
[英]When using a while loop to traverse a linked list, why does my loop iterate by twice the number of nodes in the list?
[英]Why does my loop iterate only twice?
我定義了兩個結構,當我循環設置它們的值時,它僅在printf返回時循環兩次。 有任何想法嗎?
typedef struct {
int x;
int y;
unsigned char status;
} Cell;
typedef struct {
int sizeX;
int sizeY;
Cell cell[];
} World;
int main() {
int i, x, y;
i = 0;
World grid;
grid.sizeX = 10;
grid.sizeY = 10;
for (x = 0; x < grid.sizeX; x++) {
for (y = 0; y < grid.sizeY; y++) {
Cell cell;
cell.x = x;
cell.y = y;
printf("%d,%d: ", cell.x, cell.y);
grid.cell[i] = cell;
i++;
}
}
return 0;
}
編輯:
下面給出正確的答案,感謝您的評論和您對C語言菜鳥的耐心等待!
grid.cell[]
分配任何內存空間。 您應該在循環開始前通過添加以下行來為其分配內存:
grid.cell = Cell[100];
大小100
基於以下事實: grid.sizeX = 10;
並且grid.sizeY = 10;
。 由於大小是固定的,因此無需使用malloc()
。
如果不是為grid.sizeX
和grid.sizeY
固定大小,則應添加以下行,而不是grid.cell = Cell[100];
:
grid.cell = (Cell*)malloc(sizeof(Cell) *(grid.xSize * grid.ySize ));
行World *grid = malloc(sizeof(World) + xSize * ySize * sizeof(Cell));
您添加的內容只是一種欺騙手段,還不清楚。 即使在邏輯上是正確的!
您的World
結構具有一個靈活的數組成員作為最后一個元素。 實際上,該成員沒有預留空間。 結果,您在寫入數組時會注銷結構的末尾,從而導致未定義的行為。
您需要聲明一個World *
並使用malloc
為結構加數組分配空間。
World *world = malloc(sizeof(World) + 10 * 10 * sizeof(Cell));
結果如下:
#include <stdio.h>
#include <stdlib.h>
#define LIVE 1
#define DEAD 0
#define xSize 10
#define ySize 10
typedef struct {
int x;
int y;
unsigned char status;
} Cell;
typedef struct {
int sizeX;
int sizeY;
Cell cell[1];
} World;
int main() {
int i, x, y;
i = 0;
World *grid = malloc(sizeof(World) + xSize * ySize * sizeof(Cell));;
grid->sizeX = xSize;
grid->sizeY = ySize;
for (x = 0; x < grid->sizeX; x++) {
for (y = 0; y < grid->sizeY; y++) {
Cell cell;
cell.x = x;
cell.y = y;
cell.status = DEAD;
printf("%d,%d: ", cell.x, cell.y);
grid->cell[i] = cell;
i++;
}
}
return 0;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.