2017-06-04 81 views
0

我已经定义了两个结构,当我循环设置它们的值时,它只循环两次,作为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小白正确答案!

+0

'细胞细胞[];'!! – BLUEPIXY

+0

由struct定义的单元格数组是否错误? – NoX

+3

你有没有试过用调试器代码?你一定要详细阅读[*灵活的数组成员*](https://en.wikipedia.org/wiki/Flexible_array_member),因为你现在正在做的是写出一个零大小数组的界限,导致*未定义的行为*。 –

回答

1

您的World结构有一个灵活的数组成员作为最后一个元素。实际上没有为该成员预留空间。因此,当您写入数组时,您会注销结构的结尾,导致未定义的行为。

您需要声明World *并使用malloc为结构加上数组分配空间。

World *world = malloc(sizeof(World) + 10 * 10 * sizeof(Cell)); 
+0

感谢您的回答。我现在遇到了困难,可以设置我的world.sizeX或者在我的循环中使用它。所有这一切意味着我没有理解这一切。但踢自己阅读更多关于灵活阵列。 – NoX

2

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));只是一个良知坎方式并没有太大的清晰。即使它在逻辑上是正确的!

0

下面是结果:

#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; 
} 
相关问题