Colin said:
Hi, I need to pass an array of strings to a function, but I can't get it
to work. This is what I wrote :
void a_function(char *blah[]) {
printf("%s %s %s", blah[0], blah[1], blah[2]);
}
char *blah[3];
[and then pete wrote...]
void a_function(char (*blah)[sizeof "doesn't"])
{
printf("%s %s %s\n", blah[0], blah[1], blah[2]);
}
char (*blah)[sizeof "doesn't"];
Ye gods! Please, don't frighten the questioners!
The OP
should note carefully that this code does *NOT* follow the same
design as the other couple of responses you've gotten, and I
think there's a reason for that. This way is bad.
Essentially, with two dimensions in your "array" of strings,
you have four different ways to design your data structure.
You can fix both dimensions:
char blah[3][sizeof "the longest string you'll encounter"];
strcpy(blah[0], "This");
strcpy(blah[1], "will");
strcpy(blah[2], "work");
You can fix the first dimension and let the second vary, as
others have suggested:
char *blah[3];
if ((blah[0] = malloc(sizeof "This")) != NULL);
strcpy(blah[0], "This");
if ((blah[1] = malloc(sizeof "will")) != NULL);
strcpy(blah[1], "will");
if ((blah[2] = malloc(sizeof "work")) != NULL);
strcpy(blah[2], "work");
You can vary the first dimension and fix the second, which
is what pete suggested, and will allow you to realloc() the
array as needed where the first two ways won't:
char (*blah)[sizeof "the longest string you'll encounter"];
blah = malloc(3 * sizeof *blah);
strcpy(blah[0], "This");
strcpy(blah[1], "will");
strcpy(blah[2], "work");
And finally you can vary both dimensions, which is IMHO often
the most extensible and useful solution, but does require more
bookkeeping. This is the structure with which 'argv' is defined
to work, by the way:
char **blah;
blah = malloc(3 * sizeof *blah);
if ((blah[0] = malloc(sizeof "This")) != NULL);
strcpy(blah[0], "This");
if ((blah[1] = malloc(sizeof "will")) != NULL);
strcpy(blah[1], "will");
if ((blah[2] = malloc(sizeof "work")) != NULL);
strcpy(blah[2], "work");
So there you have it. Four ways to do one simple thing, and
it's up to you to pick which one is right for this particular
problem you're solving.
HTH,
-Arthur