edmonda7
edmonda7

Reputation: 15

Is there a way to access the 2nd row of a 2d array using a pointer initialized to the first row?

Is there a way to access the 2nd row of a 2-dimensional array of char with a pointer variable set to the initial address of the array? Example:

char a[2][10];
char *b=a[0];

Is there a way to access a[1] with the b pointer?

Upvotes: 1

Views: 177

Answers (1)

Some programmer dude
Some programmer dude

Reputation: 409166

Arrays are contiguous in memory, even nested arrays of arrays. In memory, and also drawn on paper, it would look something like this:

+---------+---------+-----+---------+---------+---------+-----+---------+
| a[0][0] | a[0][1] | ... | a[0][9] | a[1][0] | a[1][1] | ... | a[1][9] |
+---------+---------+-----+---------+---------+---------+-----+---------+

If you have a pointer to the first element you can then reach every other element by simple pointer arithmetic. For example, to read a[0][2] you simply use b[2]. To get a[1][0] you have b[10]. And so on.

Upvotes: 2

Related Questions