Omats.Z wrote:
what is meaning os "char **option meet"?
char c; // c is a single char;
char *pc = &c; // pc is a pointer to char, initialized to point
to c
char **ppc = &pc; // ppc is a pointer to pointer to char, initialized
to point to pc
I get a function like this:
__________________________________
int getchoice(char *greet, char *choices[])
Note that char *choices[] is a synonym for char **choices.
Remember that when you pass an array as an argument to a function, what
actually happens is that a pointer to the first element of the array
gets passed. So if you're passing an array of char* (pointer to char),
what actually gets passed is a char ** (pointer to pointer to char).
It's fairly clear from the context of the code that choices is an array
of character strings, and this function allows you to choose one of
them based on the first character in the string. This code prints out
all of the strings in choices, and asks you to enter a single
character. It then attempts to match that character to the first
character in each of the choices. For example, if choices contained
the elements "foo" and "bar", the code would print out
foo
bar
and ask you to pick one based on the first letter. If you enter
anything other than an 'f' or a 'b', the function will print an error
message and ask you to choose again.
The statement "option = choices" is synonymous with "option =
&choices[0]".
{
int chosen = 0;
int selected;
char **option; // what is this line mean?
do {
printf("Choice: %s\n", greet);
option = choices;
The following code cycles through the choices array, printing each
element, until it hits a NULL pointer. It uses the C idiom of using a
pointer to cycle through an array rather than using an array index.
while (*option) {
printf("%s\n", *option);
option++;
}
The above code is equivalent to the following:
int i = 0;
....
while (choices[i]) // while choices[i] is not NULL
{
printf("%s\n", choices[i]);
i++;
}
selected = getchar();
option = choices;
while (*option) {
if (selected == *option[0]) {
chosen = 1;
break;
}
}
if (!chosen) {
printf("Incorrect choice, select again\n");
}
} while (!chosen);
return selected;
}
__________________________________
I know "char *option" is a pointer. But what is the ** mean? If i
delete one *, this function can't be compiled!
Right, because you're dealing with a pointer to a pointer, not a simple
pointer.
PS: i compile it by GCC 4 on ArchLinux