[英]How does the pointer in C work in this algorithm?
我有一个程序来计算字符串中辅音的最高值,如下所示:
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;
}
我对命令char *vowels = "aeiou";
感到很困惑char *vowels = "aeiou";
因为,正如我在大学学到的,除非存在增量或减量,否则指针仅指向数组中的第一个元素。 这样写有效吗? 为什么?
当你写
char* vowels = "aeiou";
指针vowels
指向“数组”的第一个元素,即“a”,你用那个指针做什么取决于你,如果你想访问元音指向的第三个元素,那么*(vowels + 2)
会给你那个-相同的地址是vowels + 2
你也可以像这样声明vowels
char vowels[] = "aeiou"; here vowels again tells where the array starts
strchr 的原型是这样的
char *strchr( const char *str, int ch );
当您传入vowels
您会告诉函数开始查找“ch”的元音开始位置。 strchr 查找直到找到字符串的末尾\\0
,如果找到它返回指向该位置的指针,即元音 + 0, +1 ,...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.