- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
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/
我有一个类型为 const char * 的变量 k,以及一个带有原型(prototype)的 glib 函数 void g_hash_table_replace(GHashTable *hash_t
我收到以下警告: cast between incompatible function types from ‘int (*)(pile *)’ {aka ‘int (*)(struct pile *
我正在阅读 an introduction to gcc其中说: ‘-Wcast-qual’ this option warns about pointers that are cast to rem
所以我有以下最小化的 C11 代码,它定义了一个包含 uint16_t 的结构(这意味着它应该对齐到 2 个字节的结构),我想将一个 char 缓冲区转换为指向该结构的指针。 随着警告全部出现,cla
如果我们有void foo(const char * const ** bar);我们用 char *** bar = malloc(...); 来调用它如foo((const char * cons
对于代码: static const char *a = NULL; abc((char **)&a); abc 方法定义为: abc(char** a) 我收到错误(警告被视为错误): erro
我知道 gcc 有一个选项 -Wcast-align,它会在每次转换指针时发出警告,从而增加目标的对齐要求。 这是我的程序: char data[10]; int ptr = *((int *)dat
编辑:问题解释得更深入 here (谢谢@Eric Postpischil)。这似乎是 GCC 中的一个错误。 首先,让我从一些上下文开始:我正在编写的代码使用了一个我无法更改的 API,在我无法更改
这是我的测试程序: #include #pragma GCC diagnostic ignored "-Wcast-qual" static void proc(char *buf) { p
static char buf[8]; void foo(){ const char* ptr = buf; /* ... */ char* q = (char*)ptr; }
有没有办法让我使用 c++11 关键字 alignas装饰函数get() .在某些情况下,我知道 get() 返回的缓冲区将包含正确对齐的浮点缓冲区。 代码: $ cat c.cxx extern c
我是一名优秀的程序员,十分优秀!