Jonas said:
Thanks to all who replied. I am trying to understand how multiple
subscripted arrays can be converted to multiple pointers.
For example, suppose I have an array
int q[3][2] = { 1,0,2,4,{3,6}};
i.e.
1 0
2 4
3 6
Now I convert it into an int[2] by
int (*r)[2] = q;
This is a pointer to an array of 2 integers.
What does this mean exactly? I can see that *r[0] is 1, *r[1] is 2 and
*r[2] is 3. Yet according to a textbook I'm using *r[0] should be 1,
*r[1] should be 0 and *r[2] should be out of bounds...
If *r has indeed three elements, then why is it called an int[2]?
Thanks,
Jonas
q can be said to be an array of two integer-arrays.
r is a pointer to a 2-integer array;
so r[0] points to the first array of two integers, r[1] to the second array of two
integers and so on.
*r[2] with r pointing to q, is equivalent to r[2][0], which is 3.
An example for printing the contents of q using a pointer to 2-integer array
[ (*r)[0] is different from *r[0] ]:
#include <iostream>
int main()
{
using std::cout;
int q[3][2] = { 1,0,2,4,{3,6}};
int (*r)[2];
for(r= q; r-q<3; ++r)
cout<<(*r)[0]<<"\t"<<(*r)[1]<<"\n";
cout<<"\n\n";
r= q;
for(unsigned i=0; i<3; ++i)
cout<<r
[0]<<"\t"<<r[1]<<"\n";
}
And my other free store code more complete:
int main()
{
int(*p1)[3]= new int[2][3];
delete[] p1;
typedef int whatever[3];
whatever *p2= new int[2][3];
delete[] p2;
typedef int what[3];
what *p3 =new what[2];
delete[] p3;
}