In C, I am using a char **
to hold a series of strings.
Here is my code:
char ** c;
//now to fill c with data ????
//cannot change:
printf ("%*s%s", 0, "", *c);
while (*++w)
printf (" %s", *c);
I do not know how to fill c
with data. What is the proper way? I cannot change the 3 printing lines because they are in an external function.
The terminology is important here, I think. The char **
doesn't "hold" a series of strings at all (unlike container objects in higher-level languages than C). The variable c
is just a pointer to a pointer to a character, and that character is going to be the first character in a nul-terminated string.
This line of thinking leads directly to the solution: If c is a pointer to a pointer to a character, that means we have to allocate some memory in which to actually hold the array of strings.
@DB_Monkey's solution posted as a comment seeks to do this but isn't quite right because it implies that code like c[0] = "cat"
copies "cat" into c[0]
, which isn't so -- the assignment applies to the pointer, not to the string. A better way would be:
int rows = 3;
char **c = calloc (rows,sizeof(char*));
c[0] = "cat";
c[1] = "dog";
c[2] = "mouse";
This also shows that it isn't necessary to show the explicit nul termination of each string.