0

I have a 2D array of strings char* d2Array[valueA][valueB].

This works fine, I am able to fill it with strings and access them. There is an issue when passing it to a function. You need to specify the second size parameter (i.e. void aFunction(char* d2Array[][valueB]). However, this is a variable, so I can't just put in a number.

If this function is in the same file, then making valueB global and writing the function as above works. However I'm not sure if this is "proper"? Or is it just working by chance? Is this actually safe to do?

Also, the problem I have is I need to pass d2Array to a function in another file. Is my only choice to make this variable all files in my program? And how would I even do that? Or is there a better way to do this?

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278

2 Answers2

4

If this function is in the same file, then making valueB global and writing the function as above works. However I'm not sure if this is "proper"? Or is it just working by chance, is this actually safe to do?

It means that your compiler supports variable length arrays. However it would be much better to declare the function like

void aFunction( size_t valueA, size_t valueB, char* d2Array[][valueB] );

without using any global variable.

To call the function you need to pass two dimensions of an array and the array itself.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
0

Variation on @Vlad from Moscow


Pass the array to aFunction() and use a variable length array as a parameter.
This is available in C99 and C23. It is optionally available in C11, C17*1.

void aFunction(size_t valueA, size_t valueB, char* d2Array[valueA][valueB]);

Note that d2Array here is still a pointer, even though the parameter looks like an array. Thus sizeof d2Array is the size of a pointer, not an array.

char* d2Array[valueA][valueB] could be replaced with char* d2Array[][valueB] yet the first better documents code's intention and some analysis tools will take advantage of that.


*1 __STDC_NO_VLA__ The integer constant 1, intended to indicate that the implementation does not support variable length arrays or variably modified type

chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256