c - 无法理解这个常量指针错误

标签 c pointers constants

我的程序需要确定指针 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;

最佳答案

这是几个标准库函数的不一致,strpbrkstrstr 等。标准要求它们返回一个指向内部找到的项的非常量指针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).

因此,您的问题的答案是,像 strpbrkstrstr 这样的函数无法在标准 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/

相关文章:

c - Linux/C 检查一个字符是否包含空格、换行符或制表符

c - Os Dev 的 PCI IDE 教程中的函数 insl 是做什么的?

c - 如何通过在 C 中传递多个参数的指针来调用函数?

c++ - 将字符串转换为 char*

python - 如何在 Python 中创建常量?

c - atof 未在单链表中转换

CodeWarrior 10.6 链接器错误

c - 使用指向结构的指针丢失内存字节

c - 理解这个示例程序

c++ - 所有 const 标记方法都隐式 [[nodiscard]] 吗?