I have a program to calculate the highest value of consonants in a string as followed:
int solve(const char* strin) {
char *vowels = "aeiou";
int solution = 0;
int current = 0;
char *c;
while(c = *strin++) {
current = strchr(vowels, c) ? 0 : current + c - 96;
if(current > solution) solution = current;
}
return solution;
}
I got quite confused with the command char *vowels = "aeiou";
because, as I've learned at university, the pointer only refers to the first element in an array unless there exists an increment or decrement. Is it valid to write like this? And why?
When you write
char* vowels = "aeiou";
the pointer vowels
points to the first element of the "array" ie 'a', what you do with that pointer is up to you, if you eg want access the third element that vowels points to then *(vowels + 2)
will give you that - the address of the same is vowels + 2
you can also declare vowels
like this
char vowels[] = "aeiou"; here vowels again tells where the array starts
the prototype of strchr looks like this
char *strchr( const char *str, int ch );
When you pass in vowels
you tell the function to start looking where vowels starts for the 'ch'. strchr looks until it finds the end of the string which is a \\0
, if it finds it returns a pointer to that location ie vowels + 0, +1 ,...
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.