Originally Posted by
Joshun
I know that to pass an array of char pointers by value you would do
, but how would you do it by reference?
in a function definition, and using the & operator with the array of char pointers doesn't seem to work.
In C there is no such thing as "pass by reference". To simulate pass by reference, a pointer is passed. Additionally, when you pass an array in C, the name of the array acts as a pointer to the start of the array. Strings are just a special array where there's a gentleman's agreement that the final element shall be '\0'.
To understand, put your example into the context of a compilable program:
Code:
void fill_strings(char *str[], int nstrings)
{
for (int i=0; i < nstrings; i++)
strcpy(str[i], "hello world");
}
void print_strings(char *str[], int nstrings)
{
for (int i=0; i < nstrings; i++)
printf("string %d: %s\n", i, str[i]);
}
int main(void)
{
char *index[10];
int i;
for(i=0; i<10; i++)
{
index[i] = malloc(20);
}
fill_strings(index, 10);
print_strings(index, 10);
return 0;
}
When you call fill_strings and print_strings, the parameter index just is an address of where this array happens to be stored in your memory. String copying only takes place once inside the actual function, not in the parameter passing.
1. By the way, you can write "char **str" in the parameter list for the same effect.
2. malloc(20) is fine