Wednesday, 15 September 2010

c - Accessing struct in 2d array outside of declaring function -



c - Accessing struct in 2d array outside of declaring function -

i'm trying access returned 2d array of structs create. can access them in func created in seem lose reference pass out. have tired one thousand ways it, doesn't seem create difference. seg faults.

my current run @ looks like:

a simple struct:

typedef struct{ int weight; } mystruct_t;

a function creates 2-d array mystruct_t's. current effort out create new variable deed pointer "map", seen in lastly 2 lines.

mystruct_t*** makegrid(int sizex, int sizey) { int i; mystruct_t **map = malloc(sizex * sizeof(*map)); if(map == null){ printf("unable set memory, exiting\n"); exit(1); }else{ ( = 0; < sizex; i++) { map[i] = malloc(sizey*sizeof(mystruct_t)); if(map[i] == null) { printf("unable set memory, exiting\n"); exit(1); }else{ printf("success!\n"); } } } mystruct_t ***mapptr = &map; homecoming mapptr; }

then in file:

void initsys(){ mystruct_t** map = *mystruct_t(100,100); map[0][0].weight = 7; //or tried //mystruct_t*** map = mystruct_t(100,100); //(*map)[0][0].weight = 7; }

output segfault. amazing how have totally forgoten c memory management , cant seem back!

any suggestions amazing.

the bug on line

mystruct_t ***mapptr = &map;

it should be:

homecoming map;

and you'll need alter homecoming type double pointer.

when homecoming "&map" returning address of variable map. variable map stored on stack, returning address invalid memory.

c memory-management malloc

No comments:

Post a Comment