### C++ Two Dimensional Array with Pointor

int sum(int (*ar2)[4], int size); // I dont know what the ar2 is going on

int main(){

int data[3][4] = {{1,2,3,4},{5,6,7,8},{9,10,11,12}};
int total = sum(data, 3)

return 0;
}
`int sum(int (*ar2)[4], int size);`

`int (*ar2)[4]` is one of the inputs to the sum function. It can be rewritten as:
`int* ar2[4]` which tells us `ar2` is an array of 4 pointers.

Another way you could write this is:
`int ar2[][4]` which helps to tell us this is a 2d array where the second dimension is 4 long.

When passing 2d arrays as a parameter, you NEED to define the size of at least one of the arrays.
 @Stewbond int (*ar2)[4] is one of the inputs to the sum function. It can be rewritten as: int* ar2[4] which tells us ar2 is an array of 4 pointers

int ( *ar2 )[4] and int* ar2[4] are two different types. The first declaration declares a pointer to an array of 4 int elements. The second declaration declares an array of 4 elements of type pointer to int.
I got your point but i am not sure :
is the int (*ar2)[4] a pointer which used (or fitted ) by {1,2,3,4} or {5,6,7,8} or {9, 10, 11, 12} ?

That means it could point to four integers of set of array
Last edited on
 @alantheweasel int sum(int (*ar2)[4], int size); // I dont know what the ar2 is going on

Any array passed to a function by value is converted implicitly to a pointer to its first element. For example

 ``1234`` ``````void f( int a[] ) {} int MyArray[10]; f( MyArray );``````

In this example MyArray as argument of function f is converted to pointer int *

So the following function declarations are equivalent

void f( int a[10] );
void f( int a[200] );
void f( int a[] );
void f( int *p );

because in fact their arguments are implicitly converted to pointers to their first elements.

In your original code there is two-dimensional array int data[3][4]. It is implicitly converted to the pointer to its first element. Element of a two dimensional array is in turn a one-dimensional array. So data[3][4] is converted to the pointer to its first row and has type int ( * )[4]
Last edited on
Topic archived. No new replies allowed.