Reputation: 731
Does (int*) arr[2] have to with typecasting? If yes, where is it used?
This problem arose when I tried to compile the follwing code :
int* arr[2];
int arr1[] = { 1,2};
int arr2[] = { 1,6};
arr[0] = arr1;
arr[1] = arr2;
by replacing
int* arr[2] with (int*)arr[2]
Thanks.
Upvotes: 2
Views: 6763
Reputation: 320797
The problem with replacing int *arr[2]
with (int *) arr[2]
in your context is that the latter no longer conforms to the C grammar for declarations. According to the structure of C grammar, in int *arr[2]
the *
is attached to arr
, not to int
. Forcing it towards int
by using extra ()
violates the suffix of a declaration.
You are allowed to use ()
in C declarations as long as it doesn't violate the syntactic structure of a declaration imposed by C grammar. For example, you can do
int *(arr)[2]; // same as `int *arr[2]`
or
int *(arr[2]); // same as `int *arr[2]`
or
int (*arr)[2]; // different from `int *arr[2]`, but still valid
but not your (int *) arr[2]
or (int) *arr[2]
. The latter are not declarations.
Upvotes: 2
Reputation: 3002
First one makes arr
as an array of pointers to int. So your arr
is a variable. That is a declaration line.
The second one: assuming that arr
is a an array (which was allready declared!), takes the value which is arr[2]
and casts a pointer to int
type on it.
Upvotes: 3