c - 显式忽略来自 -Wcast-qual : cast discards ‘__attribute__((const))’ qualifier from pointer target type 的警告

标签 c gcc warnings

static char buf[8];
void foo(){
    const char* ptr = buf;
    /* ... */
    char* q = (char*)ptr;
}

上面的代码片段将生成“警告:cast discards ‘__attribute__((const))’ qualifier from pointer target type [-Wcast-qual]”。我喜欢 -Wcast-qual,因为它可以帮助我避免意外写入我不应该写入的内存。

但现在我只想为一次事件(而不是整个文件或项目)抛弃 const。它指向的内存是可写的(就像上面的buf)。我不想从 ptr 中删除 const,因为它在其他地方使用并且保留指针(一个 const 和一个非 const)似乎是一个更糟糕的主意。

最佳答案

#include <stdint.h>

const char * ptr = buf;
....
char * p = (char *)(uintptr_t)ptr;

或者,没有 stdint.h:

char *  p = (char *)(unsigned long)ptr;

关于c - 显式忽略来自 -Wcast-qual : cast discards ‘__attribute__((const))’ qualifier from pointer target type 的警告,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13249756/

相关文章:

c - 为什么标准输入流中没有出现多个 `\n` 字符?

将 C 字符串转换为二进制表示

c - C 中的二进制搜索

c - 为什么我在 GDB 中收到消息 "Single-stepping until exit . . . which has no line number information"?

c++ - 为什么隐式转换不应用于模板化函数参数?

c - 如何禁用 GNU C 扩展?

maven - 如何使 Maven 构建在警告时失败?

c - 如何在 c 中转义 SQLite 表名称的字符串?

mysql - MariaDB 警告 : 'root@localhost' has both . .. 密码将被忽略

java - 无法找出警告背后的原因