C sizeof a passed array [duplicate] C sizeof a passed array [duplicate] arrays arrays

C sizeof a passed array [duplicate]


There is no magic solution. C is not a reflective language. Objects don't automatically know what they are.

But you have many choices:

  1. Obviously, add a parameter
  2. Wrap the call in a macro and automatically add a parameter
  3. Use a more complex object. Define a structure which contains the dynamic array and also the size of the array. Then, pass the address of the structure.


Function parameters never actually have array type. When the compiler sees

void printarray( double p[], int s )

or even

void printarray( double p[100], int s )

it converts either one to

void printarray( double* p, int s )

So sizeof(p) is sizeof(double*). And yes, you'll have to pass the size as a parameter.


The problem is that your function doesn't receive an array value; it receives a pointer value.

Except when it is the operand of the sizeof or unary & operators, or it is a string literal being used to initialize another array in a declaration, an expression of type "array of T" will be converted to type "pointer to T" and its value will be the address of the first element of the array.

Thus, when you call printarray, the type of array1 is implicitly converted from "100-element array of double" to "pointer to double." Thus, the type of the parameter p is double *, not double [100].

In the context of a function parameter declaration, T a[] is identical to T *a.

This is why you have to pass the array size separately;