I’m trying to access a returned 2d array of structs i create. I can access them with in the func they were created in but seem to lose the reference as i pass it out.
I have tired a thousand ways to do it, but it doesn’t seem to make a difference.
Always with the seg faults.
my current run at it looks like:
a simple struct:
typedef struct{
int weight;
} myStruct_t;
a function that creates a 2-d array for myStruct_t’s.
My current attempt to get it out is to make a new variable to act as a pointer to “map”, as seen in the last 2 lines.
myStruct_t*** makeGrid(int sizeX, int sizeY)
{
int i;
myStruct_t **map = malloc(sizeX * sizeof(*map));
if(map == NULL){
printf("Unable to set memory, Exiting\n");
exit(1);
}else{
for ( i = 0; i < sizeX; i++)
{
map[i] = malloc(sizeY*sizeof(myStruct_t));
if(map[i] == NULL)
{
printf("Unable to set memory, Exiting\n");
exit(1);
}else{
printf("success!\n");
}
}
}
myStruct_t ***mapPtr = ↦
return mapPtr;
}
then in another file:
void initSys(){
myStruct_t** map = *myStruct_t(100,100);
map[0][0].weight = 7;
//or i also just tried
//myStruct_t*** map = myStruct_t(100,100);
//(*map)[0][0].weight = 7;
}
output is a SegFault.
its amazing how quickly i have totally forgoten C memory management and i cant seem to get it back!
any suggestions would be amazing.
The bug is on the line
It should be:
And you’ll need to change your return type to a double pointer.
When you return “&map” you are returning the address of the variable
map. As the variablemapis stored on the stack, you are returning an address to invalid memory.