1

How can I let a pointer assigned with a two dimensional array?

The following code won't work.

float a1[2][2] = { {0,1},{2,3}};
float a2[3][2] = { {0,1},{2,3},{4,5}};
float a3[4][2] = { {0,1},{2,3},{4,5},{6,7}};

float** b = (float**)a1;

//float** b = (float**)a2;
//float** b = (float**)a3;

cout << b[0][0] << b[0][1] <<  b[1][0] <<  b[1][1] << endl;

6 Answers 6

4

a1 is not convertible to float**. So what you're doing is illegal, and wouldn't produce the desired result.

Try this:

float (*b)[2] = a1;
cout << b[0][0] << b[0][1] <<  b[1][0] <<  b[1][1] << endl;

This will work because two dimensional array of type float[M][2] can convert to float (*)[2]. They're compatible for any value of M.

As a general rule, Type[M][N] can convert to Type (*)[N] for any non-negative integral value of M and N.

Sign up to request clarification or add additional context in comments.

Comments

2

If all your arrays will have final dimension 2 (as in your examples), then you can do

float (*b)[2] = a1; // Or a2 or a3

Comments

1

The way you do this is not legit in c++. You need to have an array of pointers.

Comments

1

The problem here is that the dimensions of b are not known to the compiler. The information gets lost when you cast a1 to a float**. The conversion itself is still valid, but you cannot reference the array with b[][].

1 Comment

+1 I believe this is the reason that you can't use array indices on the float**.
0

You can do it explicitly:

float a1[2][2] = { {0,1},{2,3}};
float* fp[2] = { a1[0], a1[1] };
// Or
float (*fp)[2] = a1;

Comments

0

Try assigning b to be directly equals to a1, that's mean that the pointer b is pointing to the same memory location that pointer a1 is pointing at, they carry the same memory reference now, and you should be able to walk through the array.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.