Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inconsistent sizeof behavior in C [duplicate]

Tags:

arrays

c

sizeof

Possible Duplicate:
Behaviour of Sizeof in C

Can somebody explain why the following piece of C code behaves as it does:

#include <stdio.h>

int sizeof_func(int data[]) {
    return sizeof(data);
}

int main(int argc, char *argv[]) {
    int test_array[] = { 1, 2, 3, 4 };
    int array_size = sizeof(test_array);
    printf("size of test_array : %d.\n", array_size);
    int func_array_size = sizeof_func(test_array);
    printf("size of test_array from function : %d.\n",
        func_array_size);
    if (array_size == func_array_size) {
        printf("sizes match.\n");
    } else {
        printf("sizes don't match.\n");
    }
    return 0;
}

I expected the output to be:

size of test_array : 16.
size of test_array from function : 16.
sizes match.

But instead I got:

size of test_array : 16.
size of test_array from function : 4.
sizes don't match.
like image 828
David K. Avatar asked Dec 01 '22 05:12

David K.


1 Answers

When you pass an array as function argument it decays in to a pointer to its first element.
sizeof in function returns size of the pointer not the array.
While, sizeof in the main() returns size of the array. Naturally, both are not the same.

If you want to know the size of the array in the function you will have to pass it as an separate argument to the function.

int sizeof_func(int data[], size_t arrSize);
                            ^^^^^^^^^^^^
like image 62
Alok Save Avatar answered Dec 06 '22 11:12

Alok Save