I have defined two structs and when I loop to set their values, it only loop twice as printf return. Any ideas?
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;
}
EDIT :
Correct answer given below, thanks for comments and your patience for a C noob !
grid.cell[]
is not have been allocated any memory space. You should allocate it a memory by adding following line before starting of the loop:
grid.cell = Cell[100];
The size 100
is based on the fact that grid.sizeX = 10;
and grid.sizeY = 10;
. There is no need of using malloc()
because the size is fixed.
If size is not fixed for grid.sizeX
and grid.sizeY
then, you should add following line instead of grid.cell = Cell[100];
:
grid.cell = (Cell*)malloc(sizeof(Cell) *(grid.xSize * grid.ySize ));
The line World *grid = malloc(sizeof(World) + xSize * ySize * sizeof(Cell));
which is added by you is just a tricked way and not much clear. Even it is logically correct!!!
Your World
struct has a flexible array member as the last element. There is actually no space set aside for that member. As a result, you write off the end of the struct when you write to the array, resulting in undefined behavior.
You need to declare a World *
and use malloc
to allocate space for the struct plus the array.
World *world = malloc(sizeof(World) + 10 * 10 * sizeof(Cell));
Here is the results :
#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;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.