Page 100 - C-Language
P. 100
what if there are 30 chars instead of 20? Or 50? The answer is to add another parameter before
the array parameter:
#include <stdio.h>
/*
* Note the rearranged parameters and the change in the parameter name
* from the previous definitions:
* n (number of strings)
* => scount (string count)
*
* Of course, you could also use one of the following highly recommended forms
* for the `strings` parameter instead:
*
* char strings[scount][ccount]
* char strings[][ccount]
*/
void print_strings(size_t scount, size_t ccount, char (*strings)[ccount])
{
size_t i;
for (i = 0; i < scount; i++)
puts(strings[i]);
}
int main(void)
{
char s[4][20] = {"Example 1", "Example 2", "Example 3", "Example 4"};
print_strings(4, 20, s);
return 0;
}
Compiling it produces no errors and results in the expected output:
Example 1
Example 2
Example 3
Example 4
Passing unadjacent arrays to functions expecting "real" multidimensional
arrays
When allocating multidimensional arrays with malloc, calloc, and realloc, a common pattern is to
allocate the inner arrays with multiple calls (even if the call only appears once, it may be in a loop):
/* Could also be `int **` with malloc used to allocate outer array. */
int *array[4];
int i;
/* Allocate 4 arrays of 16 ints. */
for (i = 0; i < 4; i++)
array[i] = malloc(16 * sizeof(*array[i]));
The difference in bytes between the last element of one of the inner arrays and the first element of
the next inner array may not be 0 as they would be with a "real" multidimensional array (e.g. int
array[4][16];):
https://riptutorial.com/ 76

