I want to assign a statically allocated, multi-dimensional array to a temporary variable. Consider the following example:
void foo(int b[3][2])
{
b[1][1] = 1; // no segmentation fault
}
int main()
{
int a[3][2] = {{1, 2}, {11, 12}, {21, 22}};
foo(a);
int** c;
c = (int**)&a;
c[1][1] = 1; // segmentation fault on execution
int* d[3];
d[0] = (int*)&(a[0]);
d[1] = (int*)&(a[1]);
d[2] = (int*)&(a[2]);
d[1][1] = 1; // no segmentation fault
return 0;
}
Basically I want to do what the compiler does with the parameter b
of foo()
. But the only working solution I could come up with is d
. Is there no less complicated way?
cdecl (man page) is your friend:
cdecl> explain int b[3][2]
declare b as array 3 of array 2 of int
cdecl> declare b as pointer to array 2 of int
int (*b)[2]
So, try this:
void foo(int b[3][2])
{
b[1][1] = 1; // no segmentation fault
}
int main()
{
int a[3][2] = {{1, 2}, {11, 12}, {21, 22}};
foo(a);
int (*b)[2] = a;
b[1][1] = 1;
return 0;
}
int[3][2]
and int**
are incompatible types. You cannot cast one to another.
Try this:
int (*c)[2];
c = a; //no need to cast
c[1][1] = 1; //ok
Or you could do this (declaration as well as initialization):
int (*c)[2] = a; //no need to cast
c[1][1] = 1; //ok
Thumb of rule:
Don't use c-style cast in C++. Use C++-style cast. Had you used C++-style cast, the compiler would have told you the problem much before (ideone) (no need to run the code to see the problem):
prog.cpp:5: error: invalid static_cast from type ‘int (*)[3][2]’ to type ‘int**’
But C-style cast compiles it fine (ideone), as you already know.
And whenever you use cast, even C++-style cast, your first doubt should be the cast itself if the program doesn't work as expected.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With