How to pass 3D array of chars to a function

2019-02-15 16:53发布

问题:

I have a 3D array of chars table[][][] and I want to pass it to a void function so it can make changes to it. How can I do this?

void make(char minor[][][]);

.....
char greater[20][30][50];
make(greater);

I guess this is not gonna work.

EDIT: Another question connected with this: Say I want to make a copy function to copy a string into the array - how should I call the strcpy in the function?

void copy(char (*minor)[][])

{ char m[50] = "asdasdasd"; 
strcpy(minor[][],m);
}

回答1:

If you wanted to pass an array, just like that one, as opposed to one you've dynamically allocated with malloc (which would be a few levels of pointers, not real arrays), any of the below function prototypes will work:

  • void make(char minor[20][30][50])
  • void make(char minor[][30][50])
  • void make(char (*minor)[30][50])

The reason being you can't have something like void make(char ***minor) is because minor will only decay into a pointer to an array of arrays, it won't decay more than once so to say.



回答2:

Pass a pointer to a 2-d array:

void make(char (*minor)[30][50]);

... 
char greater[20][30][50];
make(greater);


回答3:

Edit: not a good way, see comments!

you will have to pass pointers and the size of the array,

here have a look at this post Pass multi dimension array in c