I can't figure out why output of this code is 8. I have deduced that *b x
equals to first element of array a x*4
, but I don't know why. Can someone please elaborate?
#include <iostream>
using namespace std;
int main()
{
int a[2][3] = { {4,3, 7},{2,6, 9} };
int** b = (int**)a;
cout << *b 1 << endl;
}
CodePudding user response:
Here's a more illustrative example:
#include <iostream>
using namespace std;
int main() {
int a[2][3] = { {4, 3, 7}, {2, 6, 9} };
int * b = (int *)a 4;
cout << *b << endl; // output is 6
int c[2 * 3] = { 4, 3, 7, 2, 6, 9 };
int * d = c 4;
cout << *d << endl; // output is 6
}
b
and d
are both pointers to ints. They are pointing to the base of their respective arrays plus four. With both double- and single-dimensional arrays, this is the memory corresponding to '6'.
It's that C/C is doing the math of 2 * 3 behind your back, and allocating space on the stack of 6 * sizeof(int) (ignoring padding). So the pointer arithmetic works out the same.
I'm guessing you ran in to trouble with something like:
int * b = a 4;
star.cpp:7:15: error: cannot initialize a variable of type 'int *' with an rvalue of type 'int (*)[3]'
int * b = a 4;
^ ~~~~~
1 error generated.
Which led you try the int ** b
. This isn't a pointer to an int in a double-dimensional array, it's a pointer to a pointer to an int.
Not really sure what the goal is, but a much simpler implementation would be:
#include <iostream>
using namespace std;
int main() {
int a[2][3] = { {4, 3, 7}, {2, 6, 9} };
int b = a[1][1];
cout << b << endl; // output is 6
}
CodePudding user response:
C and C views of arrays are not intuitive. In particular:
int a1[8];
int a2[4][2];
int a3[2][2][2];
These are all identical, except for how you access the memory. In addition, these assignments are all valid (though will probably generate warnings, because they're usually wrong):
int *b1 = a1;
int *b2 = a2;
int *b3 = a3;
And in particular, b3[7]
is the same as a3[1][1][1]
.
Oh, also, C and C don't care what index you use, so a1[1000000]
is allowed without question, though the underlying OS will probably not tolerate it and kill your program - unless it doesn't and you get a bug or security flaw.
This is different from, eg. Java or C#, where int a[2][2];
actually allocates one array of references to two arrays of integers, which is probably what you're thinking of.
Avoid arrays if you can, use safer constructs like vectors.