Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why sizeof(param_array) is the size of pointer?

Tags:

c

I want to get the length of an array, say int array[] = {1, 2, 3, 4}. I used sizeof to do that.

int length(int array[])
{
     return sizeof(array) / sizeof(int);
}

int main()
{
    int array[] = {1, 2, 3, 4};
    printf("%d\n", length(array)); // print 1
    printf("%d\n", sizeof(array) / sizeof(int)); // print 4
}

So, why the sizeof(array) in function length returns the pointer size of array? But in function main, it works.

And, how should I modify the length function to get an array's length?

like image 900
xiaowl Avatar asked Jul 23 '12 23:07

xiaowl


People also ask

Why is sizeof pointer 8?

The pointer is 8 bytes, because you are compiling for a 64bit system. The int it is pointing at is 4 bytes.

What does sizeof return for pointer?

The sizeof() operator returns pointer size instead of array size. The 'sizeof' operator returns size of a pointer, not of an array, when the array was passed by value to a function. In this code, the A object is an array and the sizeof(A) expression will return value 100. The B object is simply a pointer.

Does sizeof work with pointers?

The code calls sizeof() on a malloced pointer type, which always returns the wordsize/8. This can produce an unexpected result if the programmer intended to determine how much memory has been allocated. The use of sizeof() on a pointer can sometimes generate useful information.

Is Size_t always the size of a pointer?

The size of size_t and ptrdiff_t always coincide with the pointer's size. Because of this, it is these types that should be used as indexes for large arrays, for storage of pointers and pointer arithmetic. Linux-application developers often use long type for these purposes.


1 Answers

A special C rule says that for function parameters, array types are adjusted to pointer types. That means:

int length(int array[]);

is equivalent to

int length(int *array);

So when you compute the sizeof the array you are actually computing the size of the pointer.

(C99, 6.7.5.3p7) "A declaration of a parameter as "array of type" shall be adjusted to "qualified pointer to type", where the type qualifiers (if any) are those specified within the [ and ] of the array type derivation."

like image 57
ouah Avatar answered Nov 15 '22 19:11

ouah