I need to create and implement usage of the struct that contains an array inside it. How to do proper initialization and allocation of the struct and array? Here’s my current implementation that seems to work. However, not sure is it proper way and where is the struct allocated (on stack or on heap memory). IMHO a call to malloc makes to store an array on heap, however not sure about remaining struct members. Here are my structs:
typedef struct {
uint8_t objectSize;
double objectDepth;
} ObjectData;
typedef struct {
ObjectData *objectList;
double startMark;
double endMark;
} MyDataPacket;
Here is the function that fills and returns the struct:
void getMyPacket(MyDataPacket *myDataPacket, uint8_t objectNum)
{
myDataPacket->startMark = 10.0;
myDataPacket->endMark = 60.0;
myDataPacket->objectList = malloc(objectNum * sizeof(MyDataPacket));
uint8_t x;
for (x = 0; x < objectNum; x++)
{
myDataPacket->objectList[x].objectSize = x; // just test values
myDataPacket->objectList[x].objectDepth = x; // just test values
}
}
Here’s function calling part:
uint8_t objectNum = 10;
MyDataPacket myDataPacket;
getMyPacket(&myDataPacket, objectNum);
Does the struct data is mixed and placed both on stack and heap, or everything resides at one place?
If
myDataPacketis allocated on the heap, then it will all be on the heap:If
myDataPacketis an automatic variable, it will all live on the stack, including theobjectListpointer itself, the memory it points to however, will be on the heap:If it’s a global variable, it depends on whether or not it’s initialized, and whether it’s initialized to
zeroor not, but generally speaking uninitialized variables go to the.bsssection and initialized variables go to thedatasection, and of course the dynamically allocated memory will be on the heap as usual.If you’re worried about efficiency check this SO question:
Which is faster: Stack allocation or Heap allocation