开发者

(gcc) Multi-Dim Array or Double Pointer for Warning-free Compile

开发者 https://www.devze.com 2022-12-24 21:50 出处:网络
I have a function, which is called sometimes with regular, sometimes dynamic arrays. If I define the function as

I have a function, which is called sometimes with regular, sometimes dynamic arrays.

If I define the function as

function_name(int[10][10] a)

and send int** as a parameter, I get a warning. Opposite, if I declare

function_name(int** a)

and send int[][] as a parameter (after casting) I cannot access to array elements inside function开发者_Go百科.

What is the correctest way?


When an array is passed to a function, it "decays" to a pointer to its first element. So, given:

T a[10];
f(a);

In the call f(a), a is actually &a[0], i.e., a pointer, and the type is T * (the type of &a[0]).

When you have an array of arrays, the same rule applies:

T a[10][5];
f(a);

a decays to a pointer again, equal to &a[0]. a[0] is of type "array [5] of T". So, &a[0] is of type "pointer to array [5] of T", i.e., if you were to declare a pointer p to set equal to &a[0], you would do:

T (*p)[5]; /* parentheses because [] binds tighter than * */
p = &a[0];

Given the above, and assuming your array is declared in the calling code as int a[10][10];, you should declare your function as:

function_name(int (*a)[10]);

For more, see this.

There is a syntax error in function_name(int[10][10] a)—you need to specify the array size after the "variable" name: function_name(int a[10][10]). In fact, the above is equivalent to function_name(int (*a)[10]), because of the "decaying" mentioned above.

Edit: ah, I think I understand now. You cannot declare a function that takes both a "two dimensional" array and a pointer-to-pointer, for the reasons mentioned above (the "decaying" to pointer happens only once). A pointer to pointer may not point to contiguous data, and may have different number of elements in each "row". An array of arrays doesn't cannot have those properties. They are fundamentally different.


int ** and int [][] are not the same. The former is pointer to pointer to int whereas second one is 2-d array of int.

int[][] decays to int (*)[] when you pass it as argument to function.

void func(int arr[][10]) { //decays to `int (*arr)[10]` 
  printf("%d correct", arr[1][9]); //10th element of 2nd row
  //printf("%d correct", (*(arr + 1))[9]); //same as above
}

int main() {
  int (*arr)[10]; //pointer to array of ints
  arr = malloc(sizeof(int (*)[]) * 2); //2 rows & malloc will do implicit cast.

  arr[1][9] = 19;
  func(arr);

  return 0;
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号