2

Possible Duplicate:
How to pass a multidimensional array to a function in C and C++

so I have char buffer[4][50]

I need to pass it to a method void SetBuffer(char **buffer) or at least that's how i think it's suppose to be formatted.

so I do SetBuffer(buffer);? In the method I need to set each element so

void SetBuffer(char **buffer)
{
strncpy(buffer[0], "something", 50);
strncpy(buffer[1], "something else", 50);
}

how can this be accomplished properly?

Community
  • 1
  • 1
Pittfall
  • 2,751
  • 6
  • 32
  • 61

3 Answers3

3

The C++ way would be to use a proper container (e.g. std::vector<unsigned char> or std::string) as appropriate.

OTOH, if there's a particular reason to fall back on arrays, using pointers (as you already do) and passing in the dimensions explicitly are one way to do it..

dirkgently
  • 108,024
  • 16
  • 131
  • 187
  • +1 for "use a proper container". I would have answered similarly. – Drise Jun 06 '12 at 14:56
  • best way to do it, I agree as I did a bit of research and saw that it was a dangerous design to use multidimensional array in this case – Pittfall Jun 06 '12 at 19:14
2

There are many ways:

The easiest is:

void SetBuffer(char[][50] buffer)
{
strncpy(buffer[0], "something", 50);
strncpy(buffer[1], "something else", 50);

}

Guy L
  • 2,824
  • 2
  • 27
  • 37
2

Caveat: this is a C answer. Your answer looks correct to me, but a better approach is something like:

#define BUFFER_DIM_1   4
#define BUFFER_DIM_2   50

int    i;
char **buffer;

/* Create an array of pointers to the lower level */
buffer = malloc(BUFFER_DIM_1 * sizeof(char *));
for (i=0; i<BUFFER_DIM_1; i++) {
    buffer[i] = malloc(BUFFER_DIM_2 * sizeof(char));
}

You can then use as you suggest.

for the braver of heart, you could go with only two mallocs and some cleverer pointer work:

#define BUFFER_DIM_1   4
#define BUFFER_DIM_2   50

int    i;
char **buffer;

/* Create an array of pointers to the lower level */
buffer    = malloc(BUFFER_DIM_1 * sizeof(char *));
buffer[0] = malloc(BUFFER_DUM_1 * BUFFER_DIM_2 * sizeof(char));
for (i=1; i<BUFFER_DIM_1; i++) {
    buffer[i] = buffer[i-1] + BUFFER_DIM_2 * sizeof(char);
}

Finally, don't forget to free all this memory up when you no longer need it.

Neil Townsend
  • 6,024
  • 5
  • 35
  • 52