报错
#include<stdio.h>#include<math.h>
char *
find_char( char const *source, char const *chars)
{
char *temp = source;
if (source == NULL || chars == NULL)
{
return NULL;
}
else if (*source == '\0'|| *chars== '\0')
{
return NULL;
}
else
{
for (; *chars != '\0'; chars++)/*遍历chs数组*/
{
source = temp;
for (; *source != '\0'; source++)
{
if(*source == *chars)
return source;
}
return NULL;
}
}
int
main(void)
{
char sour = "ABCDEF";
char chs = "XRCQEF";
char *result = find_char(sour, chs);
printf("%c",*result);
return 0;
}
代码为什么报错 这段代码报错的原因是在调用 find_char 函数时,传入的 chars 参数是一个字符串字面量,而在函数内部的 for 循环中,尝试修改了 chars 指针的值,导致编译器报错。
在C语言中,字符串字面量是常量,其值不能被修改。而在这段代码中, find_char 函数尝试通过 chars++ 来修改 chars 指针的值,这是不允许的。因此,编译器报错。
要解决这个问题,可以将 chars 参数声明为 const char * 类型,以明确表示该参数是指向常量的指针,不可修改。修改后的代码如下:
char *
find_char(char const *source, char const *chars)
{
char *temp = source;
if (source == NULL || chars == NULL)
{
return NULL;
}
else if (*source == '\0' || *chars == '\0')
{
return NULL;
}
else
{
for (; *chars != '\0'; chars++) /*遍历chs数组*/
{
source = temp;
for (; *source != '\0'; source++)
{
if (*source == *chars)
return source;
}
}
return NULL;
}
}
这样修改后,代码将不再报错,并且能够正常运行。
页:
[1]