I'm attempting to create a dynamic array in C but I am a little confused on how to go about it. Firstly calloc() seems to be giving me strange results. I have some code as follows:
struct utmp userRec; printf("%d\n", sizeof(userRec)); //should print size of object structutmp * roster = calloc(1, sizeof(userRec)); printf("%d\n", sizeof(roster)); //should print total size of all objects in array printf("%d\n", sizeof(roster)/sizeof(roster[0])); //should print number of elements in array Now the results of the prints are:
384 8 0 This output seems odd to me, since the first print seems okay. If that is the size of that particular object then fine, but then I thought the size of the array roster would be equal to that, since calloc was told to make room for one object with the same size as userRec. Finally the result of this one is also confusing. Shouldn't the result of this calculation be one? Since again I allocated space for one struct utmp, then the result should be that I have room for one struct utmp. Not zero. Any insight into why I'm getting these results would be appreciated!
Also one more question for if/when I finally get calloc() to work for me. I would like this array to be able to grow! I read that the realloc() function could be useful for this, but I am unsure. Does realloc() maintain the state of the array while adding more space? Also does free() return a pointer to the same memory block so I could call realloc() on it again?
Thanks for any answers!
structutmp look like?rosteris a pointer, not an array. You can't know the size of the underlying data withsizeofon a pointer. You allocated 1struct utmp, so the size of the underlying data is1*sizeof(struct utmp).