指针传递的二维数组用C [英] Passing 2D Array of Pointers in C

查看:136
本文介绍了指针传递的二维数组用C的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有关我的计划,我需要一个指针二维数组传递给函数在一个单独的文件。我已经写了以下类似-syntaxed文件:

For my program I need to pass a 2D array of pointers to a function in a separate file. I've written a similarly-syntaxed file below:

#include <stdlib.h>
#include <stdio.h>

typedef struct {
  int state;
  int design;
} card_t;

card_t *cardSet[5][5];

void setFirst(card_t *cards[][]) { // <- Error: Array has incomplete element type
  cards[0][0]->state = 1;
}

int main() {
  setFirst(cardSet);  // <- Error: Type of formal parameter 1 is incomplete
  return 0;
}

当我改变code将它编译罚款所有一维数组,但对于一个二维数组,我得到上面的错误。这两种情况之间的区别是什么?

When I change the code to all 1D arrays it compiles fine, but for a 2D array I get the errors shown above. What is the difference between the two cases?

谢谢!
卡梅伦

Thanks! Cameron

推荐答案

,以一个二维数组传递给一个函数,你需要有每一个层面,但第一个的声明。
但是,您也可以只传递指针,如下所示。请注意,你应该总是(除非阵列尺寸是完全固定的,该阵列上操作功能只有数组的维度内运行)通过每个数组的长度了。

As has been mentioned, to pass a 2d array to a function, you need to have every dimension but the first declared. However, you can also just pass the pointer, as follows. Note that you should always (unless the array dimension is completely fixed and the function that operates on the array only operates within the array's dimension) pass the length of each array, too.

void setFirst(card_t ***cards, size_t n, size_t m) {
  if (n > 0 && m > 0) {
    cards[0][0]->state = 1;
  }
}

由于C [0] [0] 相同 *(*(code +通过 $ C $引用数组0)+ 0 * M),你可以通过两个指针,而不是阵列的尺寸。

Because referencing an array via code[0][0] is the same as *(*(code+0)+0*m), you can pass two pointers instead of array dimensions.

这篇关于指针传递的二维数组用C的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆