void f1()
{
int x[2] = {5, 10};
int (*p)[2] = reinterpret_cast<int (*)[2]>(x);
}
void f2()
{
int x[2] = {5, 10};
int a[1][2] = {x[0], x[1]};
int (*p)[2] = a;
}
Same as anything else:
p = &a;
When an array is an operand of the address-of operator it doesn't
decay to a pointer to the first element.
Bart.
Should be:
p = &x;
Bart.
> How do you initialize a pointer to an array?
> If I have:
>
> int x[2] = {5, 10};
>
> and
int *p = x;
> How can I get 'p' to point to 'x'?
There is an implicit conversion from int[] to int*
but it is probably better to make the conversion explicit:
int *p = (int*)x;
Try
void f1(void) {
int x[2] = {5, 10};
int *p = (int*)x;
}
He was asking about a pointer to an array of int, which is different
from a pointer to int. This is not used frequently but it can provide
better type checking when the size of an array is known at compile-
time.
> > How can I get 'p' to point to 'x'?
>
> There is an implicit conversion from int[] to int*
> but it is probably better to make the conversion explicit:
>
> int *p = (int*)x;
Superfluous casts are never better when there is an implicit
conversion.
Bart.
Edwin Robert Tisdale wrote:
>
> There is an implicit conversion from int[] to int*
> but it is probably better to make the conversion explicit:
>
> int *p = (int*)x;
>
GAK....I'm all for making the conversion explicit, but doing
so with a C-style cast opens up too many problems if x happens
to inadvertantly be an incompatible type.
int* p = static_cast<int*>(x);
if you must.
> When an array is an operand of the address-of operator it doesn't
> decay to a pointer to the first element.
Joe