I want to allocate memory to an array in a structure.
struct str
{
int *num;
};
creat()
{
str s = malloc(sizeof(str));
s->num = (int*)malloc(5*sizeof(int));
}
But after execution of line s->num = (int*)malloc(5*sizeof(int));
, if I check, sizeof(s->num)
is still the same.
Am I missing something?
s->num
is a pointer to integer and so its size will never change. You will have to keep track of the allocated block of memory that begins at s->num
in some other way.
sizeof(s->num)
gives you the size of the pointer of type int*
which won't change after your malloc
. More precisely, sizeof
is not a function but an operator and the value is given by your compiler. It's not a function that returns the size of the array allocated with malloc
.
Its because s->num
is not an array created dynamically but a pointer. Therefore it gives you the sizeof
pointer.
To find the size of dynamically allocated array, a previous SO answer gives a clue as below,
ptr + 1
as the pointer to the array. *(ptr - 1)
, which is hidden first int.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.