Passing an array as a parameter

I read in a book that int f (int P[2][4]) cannot accept A[2][3] , but B[3][4] is fine. What is the reason for this? Especially when we create dynamic allocation using pointers, this should not be a problem. thanks

+4
source share
6 answers

The reason is that functional parameters never have an array type. The compiler considers the declaration

 int f(int P[2][4]); 

as if it really said

 int f(int (*P)[4]); 

P is a pointer to an array of four int s. The type int [3][4] splits into the same type. But the type int [2][3] splits into the type int (*)[3] , which is incompatible.

Dynamic allocation is a completely different matter, and it probably does not include array types, no matter how you do it. (Array of pointers, rather).

+4
source

The reason is that int f (int P [2] [4]); is synonymous with int f (int (* P) ​​[4]); The first dimension in a function declaration is just comments.

+5
source

The reason why this is not allowed is because f(int P[2][4]) becomes f(int (*P)[4]) , so you can go through int B[3][4] , which can split into int (*B)[4] , but int A[2][3] cannot decay into int (*A)[4] , so f(int (*P)[4]) will not be accepted.

The type int (*)[3] incompatible with int (*)[4] . You can not convert to another!

However, there is a solution. You can do it:

  template<size_t M, size_t N> int f(int (&P)[M][N]) { //Use M and N as dimensions of the 2D array! } //Usage int A[2][3]; f(A); //M becomes 2, N becomes 3 int B[3][4]; f(B); //M becomes 3, N becomes 4 

It will accept all two-dimensional arrays!

+1
source

In C and C ++, if you specify that a function accepts 2-D arrays, then it must be given an explicit column size (second [] ). Line size (first [] ) is optional.

+1
source

It deals with a memory layout. The first number is basically your number of rows, and the second is the number of elements in each row. Rows are placed directly one after another. Thus, the offset is determined by the number of elements in the lines, multiplied by the number of previous lines. The compiled function will calculate line offsets based on 4 elements. When you pass an array with a different string length, these calculations will be incorrect.

+1
source

The second parameter determines the type of the 2d array, since it distinguishes the number of elements in each column.

The first parameter determines the size of the array, and since you can send a longer array to this function, it is like a passing parameter with the type: int * [3], which is similar to passing the 1st array with size 10 for functions that expect to receive an array with shorter size - and this is legal in C ++.

0
source

Source: https://habr.com/ru/post/1344311/


All Articles