+ 7

Why do we have a weird synatx in C++ to pass a 2-D array?

It's straight forward in C but in C++ it's like this int array[10][10]; void passFunc(int a[][10]) { // ... } passFunc(array); I tried passing it the way we pass it in C but it doesn't work.

19th Apr 2017, 5:58 AM
Swati
Swati - avatar
1 Odpowiedź
+ 4
It might seem a bit weird, but it's necessary for pointer arithmetic to work properly. You probably know that when you increment a pointer to an array, it moves the pointer to the next element. In order to do this, it needs to know how far it has to go to get there. When you declare an X by Y array, you're getting a contiguous section of memory laid out as X groups of Y, lined up one after the other. When you pass an array to a function like this, it decays to a pointer. As far as pointer arithmetic is concerned, the first dimension is irrelevant-- If you go out of bounds, that's on you-- it's just going to do what it's designed to do, and that's hop Y units of memory forward when you increment it. So, it needs to know what Y is. You can specify the first dimension as well if you want, but C++ does not care at all and won't do anything to enforce it.
19th Apr 2017, 6:50 AM
Squidy
Squidy - avatar