簡體   English   中英

為什么我的循環只迭代兩次?

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

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM