sizeof operator in C/Cpp language
November 6, 2012
Demo post 3
November 7, 2012

Using sizeof to get size of an Array or pointer

sizeof operator returns size in bytes. For example, In an implementation where 2 bytes (16bits) of memory is allocated to an int type, the below code will output 2

int x = 10;
printf("%d", sizeof(x)); // Output amount of memory allocated to int data type.

We talked about the sizeof operator in great detail in the last post.
If we use sizeof operator on arrays, as shown below:

int arr[10];
printf("%d", sizeof(arr)); //Will output 20

the output will be 20.
But sometimes, its not a good idea to use this operator on arrays.

The reason is, because arrays in C/C++ can be dynamic also i.e they can be on heap and if an array is on heap then a pointer will be pointing to the memory location allocated to the array, and when sizeof is applied on that pointer, it will fail.

int * ptr = (int*) malloc(10*sizeof(int));
printf("%d", sizeof(ptr));  // DON'T PRINT 20

The Above code will not print 20 (size of array). It will print the size of memory allocated to ptr.

Is it only for Arrays on heap ?
The problem is not just limited to Arrays on heap. Result of sizeof may fail even for static array (array on stack or data area), if sizeof operator is applied on a pointer which is holding the address of an array (rather than applying it on the array directly)
Consider the two cases below, both of them will output the wrong result.

int main()
{
    int arr[10];
    printSize(arr, 10);
    int *ptr2 = arr;
    printf("%d", sizeof(ptr2)); // WRONG RESULT
}
void printSize(int* ptr, int n)
{
    printf("%d", sizeof(ptr)); // WRONG RESULT
}

None of them will print the actual size of the array. They will just print the size of memory allocated to pointers. In fact, This is true for any data type. sizeof should be applied directly on the variable (or type) and not on a pointer pointing to the variable. Just that with arrays such use is more frequent.
Sometimes, it becomes more confusing, because of the way we write array arguments in the function.

void printSize(int arr[], int n)
{
    printf("%d", sizeof(arr)); // WRONG RESULT
}

Even now the output will be wrong. Because compiler never pass arrays as arguments. So even if we have defined the argument as

void printSize(int arr[] ...

The compiler will internally treat it as pointer only. The below two are treated as exactly same by the compiler

void printSize(int *arr);
void printSize(int arr[]);

Even if it is a pointer to array

void printSize(int (*ptr)[10]);

Still the sizeof operator will not print the size of array. It will only print the size of pointer, because the picture is still the same

1 Comment

  1. Nilesh Pawar says:

    Best explanation ever seen,thanks.

Leave a Reply to Anonymous Cancel reply

Your email address will not be published. Required fields are marked *