简体   繁体   中英

passing 2d array of pointers to function giving error

So I am passing a 3 by 3 array of float points. The function foo will allocate memory for each pointer. Here is the code.

#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;
      }
   }
}

Why does this does not work? It throws the following error:

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]'

So If I call foo(A) instead of foo(&A) I get this error instead:

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]'

If you are passing a two-dimensional array to a function:

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

the function's declaration must match:

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

or

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

float* A[3][3]; is a 2D array of pointers.

But you are passing address of A and receiving it as float *** . So the error.

Pass it as foo(A); and change function prototype as

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

Also, typeof should be sizeof .

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

You could try this one:

#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;
        }
    }
}

If you does not want to change the value of a variable itself in a function, you does not need to pass the address of that variable to this function. Therefore, this simpler version also works in this case:

#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;
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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