所以我在理解C中的指针时遇到了麻烦。我的问题是如何使char * find_ch_ptr返回char *。我也在整个地方遇到了演员问题。如果这里有问题,请你完整解释一下吗?
/*
* Return a pointer to the first occurrence of <ch> in <string>,
* or NULL if the <ch> is not in <string>.
*****
* YOU MAY *NOT* USE INTEGERS OR ARRAY INDEXING.
*****
*/
char *find_ch_ptr(char *string, char ch) {
char * point = (char*)(string + 0);
char * c = &ch;
while(point != '\0') {
if(point == c) return (char*)point;
else *point++;
}
return (char*)point; // placeholder
}
答案 0 :(得分:5)
while(point != '\0')
应该是
while(*point != '\0')
有些地方你需要取消引用指针而你没有这样做。喜欢
while(*point != '\0')
{
if(*point == ch)
return point;
else
point ++;
}
PS:point
是指向某个有效内存位置的指针,通过取消引用它来获取存储在该位置的值*point
答案 1 :(得分:2)
答案 2 :(得分:2)
要比较point
当前指向的字符,您需要将point
与此*
运算符取消引用
while (*point != '\0')
然后你想要比较你正在寻找的角色,但你也是这样做的。
您正在将变量ch
的地址与当前point
指向的地址进行比较,这是您需要的错误
if (*point == ch)
代替。
答案 3 :(得分:2)
这是你的代码的工作版本
请告诉你老师你从堆栈溢出中得到它
char *find_ch_ptr(char *string, char ch) {
while(*string != '\0') {
if(*string == ch)
return string;
else string++;
}
return (char*)0;
}
或K&amp; R方式
while(*string && *string!=ch);
return str;
答案 4 :(得分:2)
在检查等效性&#39; \ 0&#39;之前,需要取消引用while循环条件。
不需要c变量,可以直接使用ch参数进行while循环内的检查。
这是一个有效的例子:
#include<stdio.h>
char *find_ch_ptr(char *string, char ch) {
char *point = string;
while(*point != '\0') {
if(*point == ch)
{
return point;
}
else
{
point++;
}
}
return point; // placeholder
}
int main(int argc, char* argv[]){
printf("%c\n", *find_ch_ptr("hello world", 'r'));
return 0;
}