0

Both the commented functions return the exact same memory address. So why can I get the correct size from an array variable (pointer to first element) and I cannot get the size from an array pointer (array parameter) when there seems to be absolutely no difference (exact same memory address):

#include <stdio.h>

void arraySize(int arr[]) {
    printf("%p\n", arr); // same memory address
    printf("%lu\n", sizeof(arr) / sizeof(arr[0])); // different result
}

int main() {
    int a[] = {1,2,3,4,5};
    printf("%p\n", a);  // same memory address
    printf("%lu\n", sizeof(a) / sizeof(a[0])); // different result
    arraySize(a);
    return 0;
}
  • 1
    What `arraySize` actually receives is a pointer to the first element of the array, not an array object. In a function parameter declaration, `int arr[]` is interpreted as `int *`. – John Bode Jan 26 '20 at 17:23

2 Answers2

0

In main, a is an array, it is allocated locally, hence its size will will be always the number of elements multiplied by sizeof(int). However, when calling a function, a pointer to the array is passed (the address of the first element of the array) and stored in the stack. When printing inside the function, you are actually printing the size of a pointer, not that of an array. In 64 bit systems the size of the pointer will be 8 bytes and in 32 bit systems it will be 4 bytes.

Bes Dollma
  • 383
  • 3
  • 10
0

Because you can't pass an array as an argument to a function -- arrays are not first-class types in C and you can't do all that much with them. As a result, if you try to declare a function as taking an array as an argument, the compiler silently turns it into a pointer for you. So in the function, you don't have an array at all -- you have a pointer, and sizeof(arr) gives you the size of a pointer and not the size of the array that was converted to a pointer to pass to the function.

Chris Dodd
  • 119,907
  • 13
  • 134
  • 226
  • Why is this comment downvoted? Can someone (preferably the downvoter explain whats wrong here?) – happytomato Jan 26 '20 at 20:07
  • This is the correct answer. More specifically, the C standard requires that parameters of "array of T" type to be adjusted to "pointer to T" type (e.g. C99 standard, section 6.7.5.3 paragraph 7). – newacct Feb 17 '20 at 18:14