繁体   English   中英

将2D指针数组传递给给出错误的函数

[英]passing 2d array of pointers to function giving error

所以我要传递一个3 x 3的浮点数组。 函数foo将为每个指针分配内存。 这是代码。

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

void foo(float ***A);

int main(int argc, char **argv) {
    float* A[3][3];
    foo(&A);
}

void foo(float ***A) {
   int i,j;
   for(i=0;i<3;i++){
      for(j=0;j<3;j++){
        A[i][j] = malloc(2*sizeof(float));
        A[i][j][0] = 21;
      }
   }
}

为什么这不起作用? 它引发以下错误:

C:\Users\tony\Code\MPI>gcc test.c
test.c: In function 'main':
test.c:8: warning: passing argument 1 of 'foo' from incompatible pointer type
test.c:4: note: expected 'float ***' but argument is of type 'float *** (*)[3][3]'

因此,如果我调用foo(A)而不是foo(&A),则会收到此错误:

C:\Users\tony\Code\MPI>gcc test.c
test.c: In function 'main':
test.c:8: warning: passing argument 1 of 'foo' from incompatible pointer type
test.c:4: note: expected 'float ***' but argument is of type 'float * (*)[3]'

如果要将二维数组传递给函数:

int labels[NROWS][NCOLUMNS];
f(labels);

该函数的声明必须匹配:

void f(int labels[][NCOLUMNS])
{ ... }

要么

void f(int (*ap)[NCOLUMNS]) /* ap is a pointer to an array */
{ ... }

float* A[3][3]; 是2D指针数组。

但是,您正在传递A的地址并将其作为float ***接收。 这样的错误。

作为foo(A);传递foo(A); 并将函数原型更改为

void foo(float* A[][3]);

另外, typeof应该是sizeof

A[i][j] = malloc(2*sizeof(float));

您可以尝试以下方法:

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

void foo(float *(*A)[3][3]);

int main(int argc, char **argv) {
    float* A[3][3];
    foo(&A);
    return 0;
}

void foo(float *(*A)[3][3]) {
    int i,j;
    for(i=0;i<3;i++){
        for(j=0;j<3;j++){
            (*A)[i][j] = malloc(2*sizeof(float));
            (*A)[i][j][0] = 21;
        }
    }
}

如果您不想在函数中更改变量本身的值,则无需将该变量的地址传递给该函数。 因此,此较简单的版本在这种情况下也适用:

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

void foo(float *A[3][3]);

int main(int argc, char **argv) {
    float* A[3][3];
    foo(A);
    return 0;
}

void foo(float *A[3][3]) {
    int i,j;
    for(i=0;i<3;i++){
        for(j=0;j<3;j++){
            A[i][j] = malloc(2*sizeof(float));
            A[i][j][0] = 21;
        }
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM