2014-01-23 83 views
0

所以我有一个递归函数,要求它的类型为void,而不转向全局变量我怎样才能传递一个2d数组作为指针和解除引用一旦我编辑递归中的值功能?我已经尝试过INT *米[10] [10],我不能显示所有的代码,因为它是一个赋值,指针不分配需要的,但是全局变量是不允许传递一个二维数组作为指针C

Void h(int * m[10][10]){ 
    int x = 5; 
    int y = 5; 
    *m[x][y]=7; 
} 

这总体思路

+1

显示您的代码。 – haccks

+0

'int **'相当于int [] [],您可能必须将签名更改为像'void h(int ** array2d,int rows,int columns)' –

+4

@ichramm:'int **'不等于'int [] []'。后者不是有效的C语法,但是,如果提供了必要的维,则它可以是指向“int”(在函数参数中)或“int”(否则)数组的数组的指针。这些都不是指向'int'的指针。 –

回答

1

只要试试这个

Void h(int m[][10]) { 
    ... 

    m[x][y]=7; 
} 

打电话给你的功能无论是作为

h(&m[0]); // Passing the address of first row of 2D array m. 

h(m);  // As array names decays to pointer to first element of the array. Note that 
      // m will decays to pointer to m[0], not m[0][0]. 
+2

'h(&m [0])'是不必要的; “h(m)”就足够了。 –

+0

@EricPostpischil;是。但是如果他想传递任何一行的地址,那么他可以轻松地做到这一点。 – haccks

-1
void h(int** m) { 
    int x = 5; 
    int y = 7; 
    m[x][y] = 7; 
} 

int main(int argc, char* argv[]) 
{ 
    int** a = (int **)malloc(10*sizeof(int *)); 

    for (int i=0; i<10; i++) { 
     a[i] = (int *)malloc(10*sizeof(int)); 
    } 

    h(a); 

    return 0; 
} 
+1

声明为“int ** m”的参数不能接受指向二维数组(数组数组)的指针,也不能接受数组通常的自动转换,即指向其第一个元素的指针。 –

+1

这是错误的。数组到指针的下降规则不是递归的; 'int m [10] [10]'衰变成int(*)[10]'。 –

+0

答案中的代码究竟有什么问题? – chessweb

1

这一切都取决于你如何申报应该是传递给函数的数组。

如果你宣布它这样

int my_array[10][10];  // array declaration 

然后

void fun (int m[10][10]); // prototype of a function accepting my_array 
fun (my_array);   // calling the function 

是你在找什么。

在这种情况下,m恒定指针,如10×10的二维数组访问100角连续int秒。

其他可能的变化:

int * my_array[10]; 
for (i = 0 ; i != 10 ; i++) my_array[i] = malloc (10*sizeof(int)); 

void fun (int m[10][]); // these syntaxes are equivalent 
void fun (int * m[10]); 

或者这一个:

int ** my_array; 
my_array = malloc (10 * sizeof (int*)); 
for (i = 0 ; i != 10 ; i++) my_array[i] = malloc (10*sizeof(int)); 

void fun (int m[][]); // these syntaxes are equivalent 
void fun (int * m[]); 
void fun (int ** m); 

或此病理之一:

int (* my_array)[10]; 
int a0[10]; 
int a1[10]; 
/* ... */ 
int a9[10]; 
my_array = malloc (10 * sizeof (int *)); 
my_array[0] = a0; 
my_array[1] = a1; 
/* ... */ 
my_array[9] = a9; 

void fun (int m[][10]); // these syntaxes are equivalent 
void fun (int (* m)[10]); 

如果你的变量声明和函数原型并不一致,你将不会从你的函数内正确地访问数组,读取不连贯的值,并搞砸了你的记忆和可能崩溃,如果你试图修改一个元素。

如果您没有更好的办法,您可以阅读this little essay of mine on the subject了解更多详情。