2

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);
}
Gero Perov
  • 35
  • 1
  • 6
  • 2
    I think you can only pass around 3D static arrays if you know the exact size of the first two dimensions. – Andrew Kolesnikov Dec 05 '11 at 04:02
  • There are *many* question on multi-dimensional array on the site already. Most of them address 2D, but the methods extend trivially. Note that c99 makes this much easier than the earlier standard, so use it if you've got it. – dmckee --- ex-moderator kitten Dec 05 '11 at 04:39
  • 1
    @AndrewKolesnikov - Actually, you can pass around multi-dimensional arrays if you know the exact size of all but the *first* (not last) dimension. – Jim Buck Dec 05 '11 at 04:47
  • @GeroPerov if you come up with a new question, stackoverflow form is to make a new question out of it – Dave Dec 05 '11 at 05:25
  • @GeroPerov: With your new question, you have to specify how you want to copy a string in `minor` - which part of the "3D" array (ie. `minor[0][0]` - you have 20 arrays of 30 arrays of 50 `char`s, you need to be specific). It's best if, as Dave said, you create a new question and include as much detail as you can about what you want to accomplish and the desired output. – AusCBloke Dec 05 '11 at 08:19

2 Answers2

7

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.

AusCBloke
  • 18,014
  • 6
  • 40
  • 44
2

Pass a pointer to a 2-d array:

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

... 
char greater[20][30][50];
make(greater);
Juha Syrjälä
  • 33,425
  • 31
  • 131
  • 183
Dave
  • 10,964
  • 3
  • 32
  • 54
  • 1
    Thanks! Where did you learn this stuf? We have a C-course at the university, but nothing like this is being teached, and it's important. Any books?Materials? Thanks in advance! – Gero Perov Dec 05 '11 at 04:03
  • 1
    K&R. It's pretty much the definitive book on C. Between that and a lot of practice, many of c's oddities become 2nd nature. – Dave Dec 05 '11 at 04:05