I want to allocate memory for strucs such below
typedef struct {
int *buffer;
int length;
int dsn;
int handle;
} myStr;
which one is correct?
myStr *pStr = malloc(sizeof(myStr)+lenOfBuff);
or
myStr *pStr = malloc(sizeof(myStr));
I saw in some Examples that use the first one, but it seems a little strange for me. Does it have to allocate memory for data Buffer at the same time??
It depends.
If you want to change the length of the buffer after creation, you need to allocate it separately. If not, you can co-allocate the two blocks in a single
malloc()call, which might be slightly more efficient.The co-allocation would look like so: