Jake Wright
Jake Wright

Reputation: 373

Pointers and multidimensional arrays in C++

I have this piece of code:

#include <iostream>
int main()
{
int ia[3][4]; // array of size 3; each element is an array of ints of size 4
int (*p)[4] = ia; // p points to an array of four ints
p = &ia[2]; // p now points to the last element in ia
return 0;
}

How does p point to the last element in ia?

Upvotes: 1

Views: 66

Answers (2)

Killzone Kid
Killzone Kid

Reputation: 6240

int (*p)[4] = ia; // p points to an array of four

p = &ia[2]; //p now points to the last element in ia

If you have array

int ia[3][4] = { { 1,2,3,4 },{ 5,6,7,8 },{ 9,10,11,20 } };

then after int (*p)[4] = ia; pointer p will be pointing to {1,2,3,4} and after p = &ia[2];, p will be pointing to { 9,10,11,20 }

If you want a pointer to the first element of the last array, from your example:

int ia[3][4] = { { 1,2,3,4 },{ 5,6,7,8 },{ 9,10,11,20 } };
int(*p)[4] = ia; // p points to { 1,2,3,4 }
p = &ia[2]; // p points to { 9,10,11,20 }
std::cout << *(p[0]) << std::endl; // 9, because p[0] points to the first int of { 9,10,11,20 }
std::cout << *(p[0]+3) << std::endl; // 20, because p[0]+3 points to the last int of { 9,10,11,20 }

Upvotes: 1

eerorika
eerorika

Reputation: 238461

How does p point to the last element in ia?

ia contains 3 elements. Each element is an array of 4 integers. ia[2] is the last element i.e. the last array of 4 integers.

Upvotes: 3

Related Questions