Short answer: It isn't allocated for you.
Slightly longer answer: The subcells
pointer is uninitialized and may point anywhere. This is a bug, and you should never allow it to happen.
Longer answer still: Automatic variables are allocated on the stack, global variables are allocated by the compiler and often occupy a special segment or may be in the heap. Global variables are initialized to zero by default. Automatic variables do not have a default value (they simply get the value found in memory) and the programmer is responsible for making sure they have good starting values (though many compilers will try to clue you in when you forget).
The newCell
variable in you function is automatic, and is not initialized. You should fix that pronto. Either give newCell.subcells
a meaningful value promptly, or point it at NULL
until you allocate some space for it. That way you'll throw a segmentation violation if you try to dereference it before allocating some memory for it.
Worse still, you are returning a Cell
by value, but assigning it to a Cell *
when you try to fill the subcells
array. Either return a pointer to a heap allocated object, or assign the value to a locally allocated object.
A usual idiom for this would have the form something like
Cell* makeCell(dim){
Cell *newCell = malloc(sizeof(Cell));
// error checking here
newCell->subcells = malloc(sizeof(Cell*)*dim); // what if dim=0?
// more error checking
for (int i=0; i<dim; ++i){
newCell->subCells[i] = makeCell(dim-1);
// what error checking do you need here?
// depends on your other error checking...
}
return newCell;
}
though I've left you a few problems to hammer out..
And note that you have to keep track of all the bits of memory that will eventually need to be deallocated...
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…