在下面的虚拟示例中,我收到了一条警告,但我不明白如果不使用 int *_str = (int*)str
显式定义指针,我该如何摆脱它:
#include <stdlib.h>
#include <stdint.h>
void foo(void *str, int c, size_t n) {
for (size_t i = 0; i < n; i++)
*((int*)str++) = c;
}
这是我在 gcc
中得到的:
gcc -c -std=c99 -Wpointer-arith test.c
test.c: In function ‘mymemset’:
test.c:7:20: warning: wrong type argument to increment [-Wpointer-arith]
*((int*)str++) = c;
^
我的代码有什么问题?
注意
我知道这个问题和这个很相似 one ,但它并没有解释为什么我不能这样做以及为什么我会出错。
最佳答案
str
是指向 void
的指针。由于 void
很好,void,并且没有大小,可怜的编译器怎么可能理解你所说的 str++
的意思?
str++
应该使 str
指向下一个对象,但是由于类型 void
不能是任何对象的类型 str++
没有意义。
虽然您转换为 int *,但++ 比转换更“绑定(bind)”(“优先级”一词在这里混淆)。
关于c - 递增的错误类型参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42855409/