简体   繁体   中英

Allocate memory for an array inside a structure

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,

  1. As you're trying to allocate array of 5 integers, add 1 more integer to it and make it 6.
  2. Hide the size in the first integer and return ptr + 1 as the pointer to the array.
  3. Now you can get the size at *(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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM