I am testing the sizeof operator. In two cases in my code, I get the size of the pointer (I think). In the other cases I get
When an array is passed to a function, what's actually happening is that a pointer to the first element in the array is being passed. Put another way, the array decays into a pointer to the first element.
In these two declarations:
void test (char arrayT[]);
void test2 (char *arrayU);
arrayT
and arrayU
are of exactly the same type due to this decay, and sizeof
will return the same value for both, i.e. the size of a char *
.
Contrast the above with this:
char array1[] = "a string";
char *array2;
Where array1
is actually an array of size 9, while array2
is a pointer whose size (on your system) is 4.
Because of this, there is no way to know the length of an array passed to a function. You need to pass in the size as a separate parameter:
void test (char arrayT[], size_t len);