1

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?

5
  • What exact sort of "how" are you looking for? Commented Jan 6, 2018 at 21:22
  • I would think it would point to the first element in the third row. How come I don't have any additional dimension to the initiaziler of ia and yet it points to the last element in the last row, not the first? Commented Jan 6, 2018 at 21:26
  • 2
    It doesn't point to the last element in the last row. The last element of ia is the third row itself. Commented Jan 6, 2018 at 21:27
  • The elements of ia are pointers to int[4] arrays. ia has 3 elements. the last one is ia[2]. So the element in your case is not a number, its an array. Commented Jan 6, 2018 at 21:28
  • Oh, okay, so by "last element" it doesn't mean ia[2][3], but the third row. Thanks a lot! Commented Jan 6, 2018 at 21:29

2 Answers 2

3

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.

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

Comments

1

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 } 

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.