c和指针的一个6.1习题:在字符串str中字符,查找在字符串source中位置并打印出来。
#include <stdio.h>
#include <stdlib.h>
#ifndef NULL
#define NULL 0
#endif
char *find_char ( char const *source, char const *chare)
{
char *ret;
ret = NULL;
if (*source == '\0' || *chare == '\0') {
return ret;
}
char temp;
char const *p;
p = NULL;
while((temp = *chare++) != '\0') { /*遍历chare字符串*/
p = source;
while(*p != '\0')
{
if (*p = temp) {
return p; /*警告:把char const类型赋值给了char类型了*/
else
p++;
}
}
return ret;
}
int main ()
{
char const *chare = "XYZ";
char const *source = "ABCDEF";
char *result;
result = find_char( &source, &chare);
if (result == NULL)
printf("Not find\n");
else
printf("Find %c\n", *result);
return 0;
}
编译报警告:把char const的字符赋值给了char类型,有可能会发生修改错误。
不知道怎么修改。
这样改就好了。
#include <stdio.h>
#include <stdlib.h>
#ifndef NULL
#define NULL 0
#endif
char const *find_char ( char const *source, char const *chare)
{
char *ret = NULL;
if (*source == '\0' || *chare == '\0') {
return ret;
}
char temp;
char const *p;
p = NULL;
while((temp = *chare++) != '\0') { /*遍历chare字符串*/
p = source;
while(*p != '\0')
{
if (*p = temp) {
return p; /*去掉了:警告:把char const类型赋值给了char类型了*/
else
p++;
}
}
return ret;
}
int main ()
{
char const *chare = "XYZ";
char const *source = "ABCDEF";
char const *result = find_char( &source, &chare);
if (result == NULL)
printf("Not find\n");
else
printf("Find %c\n", *result);
return 0;
}