我的程序需要确定指针 s1 中是否有 s2 中的任何字符,然后返回指向 s1 中该位置的指针,否则返回 NULL。
#include <stdio.h>
char * strpbrk(const char *, const char *);
int main(void){
const char *s1 = "hello";
const char *s2 = "world";
printf("Repeated character in s1 is %p", *strpbrk(s1, s2));
}
char * strpbrk(const char * s1, const char * s2){
char *p1, *p2;
p1 = s1;
p2 = s2;
for(; *p1 != '\0'; p1++){
for(; *p2 != '\0'; p2++){
if(*p1 == *p2){
break;
}
else{
return '\0';
}
}
}
return p1;
}
不断收到此错误:
test.c: In function ‘strpbrk’:
test.c:16:5: warning: assignment discards ‘const’ qualifier from pointer target type [-Wdiscarded-qualifiers]
p1 = s1;
^
test.c:17:5: warning: assignment discards ‘const’ qualifier from pointer target type [-Wdiscarded-qualifiers]
p2 = s2;
最佳答案
这是几个标准库函数的不一致,strpbrk
、strstr
等。标准要求它们返回一个指向内部找到的项的非常量指针const 限定的字符串。当标准委员会决定向这些库函数的参数添加常量正确性而不是返回类型时,我不知道他们在吸烟什么。
您无法在标准 C 中可靠地实现此类函数,因为不允许您从“限定类型指针”转换为“类型指针”。 C11 6.7.6.1:
For two pointer types to be compatible, both shall be identically qualified and both shall be pointers to compatible types.
这就是为什么您不断收到编译器警告的原因。违反此规则被(非规范性)附件 J 列为未定义行为:
Two pointer types that are required to be compatible are not identically qualified, or are not pointers to compatible types (6.7.6.1).
因此,您的问题的答案是,像 strpbrk
和 strstr
这样的函数无法在标准 C 中安全且可移植地实现。它们必须通过使用非- 标准语言扩展或其他编程语言。
合理的解决方案是忽略标准指定的函数声明并使用有理函数声明。要么
char* strpbrk_rw (char* s1, const char* s2); // read/write parameter
或
const char* strpbrk_ro (const char* s1, const char* s2); // read-only parameter
关于c - 无法理解这个常量指针错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42659239/