How can I pass a multidimensional array as a pointer in c

368 views Asked by At

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?

3

There are 3 answers

2
dirkgently On BEST ANSWER

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..

0
Guy L On

There are many ways:

The easiest is:

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

}

1
Neil Townsend On

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.