3

I'm a beginner and I'm trying to understand how multidimensional arrays work.

So far, I've come this code snippet that i do not understand:

int arr[] = { 3, 5, 6, 7, 9 };
int (*ptr)[5] = &arr;

Ok so. I understand that ptr is a pointer pointing to an array of 5 elements.

But what is the '&' doing?? Is ptr pointing to the beginning address of 'arr'? But isnt 'arr' already an address? Why is there an '&' then? Also. What is the significance of the indexing 5? Because when i try to give any other number besides 5, it throws an error.

I'm sorry if all this sounds silly but I'm so confused! Help!

2
  • I didn't get you? Commented Apr 11, 2019 at 16:32
  • You do not index with the 5 here, but you declare a pointer to an array with 5 elements. Commented Apr 11, 2019 at 16:33

2 Answers 2

1

Here, you have a variable arr with type array of 5 int:

int arr[] = { 3, 5, 6, 7, 9 };

Here, you declare a pointer ptr to array of 5 int:

int (*ptr)[5]

This gets the address of arr with type pointer to array of 5 int

&arr

and this assignment works, since the pointer types are equal:

int (*ptr)[5] = &arr;

Now if you change the type of ptr to another type, i.e. pointer to array of 6 int:

int (*ptr)[6];

then the assignment no longer works, since the pointer types mismatch now. This is why you get an error.

Note: the [5] in this code does not index anything, but is just a part of the variable declaration (number of elements in the array)

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

3 Comments

Ok so for int a[3];, the address of a is a pointer to array of 3 elements? (Or does that hold good only when you assign values to the elements at the time of initialisation itself? )
@bobthebuilder Yes, &a is of type int (*)[3] then.
Ok makes sense. Thank You!
0

Your array only has one dimension, so it's not multidimensional.

Your array has 5 elements, and since arrays are zero-based, accessing element [5] (the sixth element) actually results in undefined behavior.

arr is not an address, it's an array. & is the address-of operator.

1 Comment

Here's the thing. The second line of the code. Isn't it kinda equivalent to *p=a;?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.