2

Suppose I have 2D array such as:

A[3][10]; 

Does it mean it is an array of 3 pointers? (from which everyone points to 1 of 10 elements)

So A is a pointer which points to 1 of 3 pointers?

2

2 Answers 2

4

No.

It means it's an array of 3 arrays, where each of these is an array with 10 elements.

If it helps, you can think of it as one big 1D array of 30 elements with compiler support that allows you to use 2D indexing (the compiler performs the necessary calculations to turn your indexes into a flat index). In fact, this is actually how it is implemented.

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

7 Comments

No it's not, it's still a single array with a bit of syntactical sugar. Your "if it helps" part is how it actually works.
Are you sure that c++ guarantees that A[0][9] is contiguous to A[1][0] in memory?
@galinette, Yes, it's definitely contiguous.
@BonzaiThePenguin It's how it's implemented (I've added this to my answer), but it is generally a good idea to abstract such details. See stackoverflow.com/questions/22143494/… for an example of a good question about this.
I can't understand how **A+10 would point to the same as A[1][0] does it mean A witch is pointer to pointer is incremented or a pointer it points to
|
2

No, it is not an array of 3 pointers. Look at the memory representation:

A[3][10] = |_|_|_|_|_|_|_|_|_|_| |_|_|_|_|_|_|_|_|_|_| |_|_|_|_|_|_|_|_|_|_| ^ ^ px px+4 

That is, A is an array of 3 arrays which contains 10 elements each. These three arrays are contiguous in memory. That is, the element after A[0][9] is A[1][0].

And of course, as chris said, don't confuse arrays with pointers.

3 Comments

I don't think you should be stating that A[0][10] is the same as A[1][0] as the first expression has undefined behaviour. You could legitimately say 'the element after A[0][9] is A[1][0]' and not even I could take exception to that.
I understand that writing an index outside of the array is undefined behaviour. But here, A[0][10] boils down to *(*A+10) which is well inside the given space. So does it remain undefined? :)
It is *(*A+10) rather than **(A+10), for one thing (because **(A+10) is accessing wildly outside the array). But since *A or A[0] is of type 'pointer to array of 10 int', any use of subscript 10 is accessing out of bounds and should be avoided. While I don't know of a system where there'd be a problem, accessing an array element that is out of bounds leads to undefined behaviour and should not be taught.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.