Search code examples
arrayscpointersimplicit-conversionsizeof

Question regarding size of integer pointer variables in C


I wrote this really simple program to check the size of integer pointers in c.

#include <stdio.h>

int main(void) {
    
    int i = 10;
    int* i_ptr = &i;    
    int arr[3] = {13, 14, 15};

    printf("\n ... Size of an integer pointer is: %ld bytes and %ld bits ...", sizeof(i_ptr), 8*sizeof(i_ptr));    
    printf("\n\n ... Size of a 3-element integer array is: %ld bytes and %ld bits ...\n\n", sizeof(arr), 8*sizeof(arr));
    printf(" ... Size of the *arr element is: %ld bytes and %ld bits ...\n\n", sizeof(*arr), 8*sizeof(*arr));

    return 0;
}

The output regarding the size of the different variables was:

... Size of an integer pointer is: 8 bytes and 64 bits ...

... Size of a 3-element integer array is: 12 bytes and 96 bits ...

... Size of the *arr element is: 4 bytes and 32 bits ...

Now, my questions is the following. As I am running a 64-bit linux operating system, I understand that the size of an integer pointer variable is 64 bits long. The size of the integer array is 12 bytes since an integer takes 4 bytes of memory and the array consist of 3 integers. However, when I think that an array is basically a pointer in C and the variable of the array points to the first element of the array, I supposed that the size of the array would resemble the size of the corresponding pointers. Yet, I also understand that this wouldn't mean that the size of the array would be 24 bytes long as the size of 3 integer pointers. This seems kind of confusing to me, so any advice would be appreciated.


Solution

  • Arrays are not pointers. If you declare an object of an array type then its size is equal to the number of bytes occupied by the array elements.

    But array designators used in expressions with rare exceptions as for example used as operands of the sizeof operator are converted to pointers to their first elements.

    From the C Standard (6.3.2.1 Lvalues, arrays, and function designators)

    3 Except when it is the operand of the sizeof operator or the unary & operator, or is a string literal used to initialize an array, an expression that has type ‘‘array of type’’ is converted to an expression with type ‘‘pointer to type’’ that points to the initial element of the array object and is not an lvalue. If the array object has register storage class, the behavior is undefined.