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/