Search code examples
arrayscsizeof

I do not understand array decay in C..it seems selective


While I pass B[2][3] 2D Array in a function pointer decay is expected.

However that seems to be happening selective only in what I pass as a parameter syntactically.

Here is my code:

#include<stdio.h>

void printArray(int B[][3])
{
     printf("sizeof(B) is : %u\n", sizeof(B)); //When arrays are passed to functions they decay into pointers. 
     printf("sizeof(B[0]) is : %u\n", sizeof(B[0])); //But here I get an array-pointer.Why there is no array to pointer decay here?See results Below.
}

int main(int argc, char* argv[])
{
    int B[2][3] = { {2,3,6},{4,5,8} };
    
    printf("sizeof(B) is : %u\n", sizeof(B));
    printf("sizeof(B[0]) is : %u\n", sizeof(B[0]));

    printArray(B);

    return 0;
}

Here are my results:

sizeof(B) is : 24
sizeof(B[0]) is : 12
sizeof(B) is : 4
sizeof(B[0]) is : 12

C:\Users\Strakizzz\Desktop\C\My Codeschool Projects\Pointers in C?C++\Debug\FunctionsPointersScopeMayhem.exe (process 20660) exited with code 0.
To automatically close the console when debugging stops, enable Tools->Options->Debugging->Automatically close the console when debugging stops.
Press any key to close this window . . .

I was expecting while printing sizeof(B[0]) from my called function to get 4 bytes as well like when i calculated the sizeof(B) in the same function:

void printArray().

.Why do I get these results, what is happening under the hood?


Solution

  • The array "decay", which occurs in many contexts in which an array type is used, replaces the array type with a pointer to the first element of an array. So an int a[5] decays to an int *.

    For a two-dimensional array, i.e. an array of arrays, it works like this: int B[2][3] decays to an int (*)[3], which is a pointer to an array of three int. That's because B is an array of two elements, with each element being an array of three int.

    In printArray, the compiler automatically adjusts the B parameter to have type int (*B)[3]. B is a pointer, which on your machine has size 4, and B[0] has type int [3], so it has size sizeof(int) * 3 which on your machine is 12. So printArray prints 4 and 12.

    Portability note: Using %u to print a sizeof value, which has type size_t, is not portable. Instead, use %zu, which is portable.