Passing a multidimensional array

I'm trying to pass a two-dimensional array to a function. The function is defined as:

long foobar(char foo[][CONST]);

I have to create that array dynamically. Currently I do that this way:

char* bar = new char[count * CONST];

But when I'm trying to pass the array I get a type conversion error. I tried a lot of different ways to pass the pointer and/or to allocate the memory, but apparently I didn't find the right way or combination of definition, allocation, casting and calling.

Unfortunately, I cannot change the definition of the function, which (IMHO) is pretty stupid. :(
closed account (o3hC5Di1)
Hi there,

char foo[][CONST] and char* bar are not the same.

The first is a 2 dimensional array char** bar, the second a single dimension array.

So if you need a 2 dimensional array, you will have to declare bar as one:

char** bar = new char[100][count * CONST];

Hope that helps.


Never mind - see Duoas' post below :)

All the best,
NwN
Last edited on
No, that's nonsense.

char foo[][CONST] is not the same as char**bar.

Multidimensional arrays are difficult to mess with. But the important fact is that any MD array is actually just a 1D array with special syntax to access it. Use this fact to create and cast. Oh, and don't forget to pass the size of the first dimension as argument to your function:

 
long foobar(char foo[][CONST], int size);
1
2
3
4
5
char* bar = new char[count * CONST];

foobar( (char(*)[CONST])bar, count );

delete [] bar;

Hope this helps.
It works! Thanks a lot Duoas. :)

Passing the size of the array is already there. I shortened the definition in my example to the important parts.

I like that cast, that's why I love C.
Topic archived. No new replies allowed.