Search code examples
cstructuredynamic-memory-allocation

Does the size of a pointer to a structure increase as memory is allocated for that structure?


Let's say I have the following structure:

  typedef struct
  {
  int length ;
  int * data ;
  } Array ;

And in my main function I do the following:

 int length = 10;
 char * filename = " data ";
 // create an object
 Array * arrptr1 = NULL ;
 printf (" sizeof ( arrptr1 ) = % d \ n ", ( int ) sizeof ( arrptr1 ));
 arrptr1 = malloc ( sizeof ( Array ));
 printf (" sizeof ( arrptr1 ) = %d , sizeof ( Array ) = % d \ n" ,
 ( int ) sizeof ( arrptr1 ) , ( int ) sizeof ( Array ));
 // allocate memory for the data
 arrptr1 -> length = length ;
 arrptr1 -> data = malloc ( sizeof ( int ) * ( arrptr1 -> length ));
 printf (" sizeof ( arrptr1 ) = %d , sizeof ( arrptr1 -> data ) = % d \ n " ,
 ( int ) sizeof ( arrptr1 ) , ( int ) sizeof ( arrptr1 -> data ));

What would be printed for each of the print statements?

I know for the first print, sizeof(arrptr1) would just be a garbage value.

For the second print, would sizeof(arrptr1) = 8 and sizeof(Array) = 8 as well?

What would the third print statement output?


Solution

  • I know for the first print, sizeof(arrptr1) would just be a garbage value.

    No, it will be the size of the pointer. If, for example, it's a 64-bit platform where all pointers are 8 bytes, it will print 8. If it didn't give you a sensible value, how could you know how much memory to allocate to store an instance of the type?

    For the second print, would sizeof(arrptr1) = 8 and sizeof(Array) = 8 as well?

    Not likely. Since an Array has an integer and a pointer, it will likely by 16 bytes on platforms with 8 byte pointers and 4 byte integers. (If it was 12 bytes, an array of Arrays would have every other element unaligned.)

    What would the third print statement output?

    It is a common beginner mistake to think that sizeof cares what is in the things whose sizes you ask it about. It just gives the size of the relevant types.

    char * j;
    sizeof(j);    // equivalent to sizeof(char*)
    sizeof(*j);   // equivalent to sizeof(char)
    
    j = "hello";
    sizeof(j);    // still equivalent to sizeof(char*)
    sizeof(*j);   // still equivalent to sizeof(char)
    
    j = malloc(32);
    sizeof(j);    // still equivalent to sizeof(char*)
    sizeof(*j);   // still equivalent to sizeof(char)
    

    You can think of sizeof as telling you how many characters you would need to hold an instance of the type of its parameter.