1

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?

Maxime Chéramy
  • 17,761
  • 8
  • 54
  • 75

3 Answers3

1

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.

Ivaylo Strandjev
  • 69,226
  • 18
  • 123
  • 176
1

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.

Community
  • 1
  • 1
Maxime Chéramy
  • 17,761
  • 8
  • 54
  • 75
0

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.
Community
  • 1
  • 1
Sunil Bojanapally
  • 12,528
  • 4
  • 33
  • 46