Reputation: 51
I want to understand where exactly in code an array gets converted to a pointer. For example:
void foo( int* pData, int len){}
int main(void){
char data[] = "Hello world";
foo( (int*)data, sizeof(data));
return 0;
}
I know that an array decays to a pointer to the first element if it is assigned to a pointer. However in the example above, I typecast the array data to int* first before passing it in function and assigning it to a pointer. Does the conversion/decay to pointer occurs at the typecasting point ? If so, isn't it true to say that the typecasting operation has the same effect as using the assignment operator with respect to array conversion/decay? Also would sizeof(data) be equal to the address length or array length?
Thank you for help!
Upvotes: 3
Views: 128
Reputation: 3041
Outwith the declaration, you can consider data
to be equivalent to a pointer to the start of the array, but with the following exceptions:
sizeof(data)
will give you the size of the array in bytes._Alignof(data)
will be the same as _Alignof(*data)
(and both give you the alignment of the type of the array elements)&data
has the same value as just data
, but have a type of char (*)[sizeof(data]
so arithmetic will use the full size of the array. Eg &data+1
will give you the address after the whole array rather than the address of the second element. See How come an array's address is equal to its value in C?char *const
).When you call your function, you are taking the value of data
(ie the address of the start of the array) and typecasting to an int *
. The resulting int *
behaves like any other int *
and the exceptions don't apply, this is the 'decay'.
Upvotes: 0
Reputation: 224112
The conversion of arrays to pointers in C is spelled out in section 6.3.2.1p3 of the C standard:
Except when it is the operand of the
sizeof
operator, the_Alignof
operator, or the unary&
operator, or is a string literal used to initialize an array, an expression that has type "array of type" is converted to an expression with type "pointer to type" that points to the initial element of the array object and is not an lvalue. If the array object has register storage class, the behavior is undefined.
This means that the array is immediately converted to a pointer anywhere it is used except for the three cases listed above.
So applying the above to (int*)data
, data
is the operand of the typecast operator. Since this operator is not one of the ones listed above, data
in this expression is converted from char [12]
to char *
, then the cast converts the char *
to an int *
.
Also, as mentioned above, the array is not converted when passed to sizeof
. This means sizeof(data)
evaluates to the size of char [12]
which is 12.
Upvotes: 1