我正在使用gcc 4.7.2编译C程序.我总结了一个带有一些偏移的void*类型的地址.(void*+ size)应该发出警告.如果不是,那么如果size是1并且大小是50,它将被添加到多少字节.我唯一关心的是应该警告我们正在添加一些东西到void指针?
12 int size = 50;
/*Allocate a block of memory*/
14 void *BlockAddress = malloc(200);
15 if(!BlockAddress)
16 return -1;
17 address1 = (int *)BlockAddress;
18 address2 = BlockAddress + 1*size;
19 address3 = BlockAddress + 2*size;
Run Code Online (Sandbox Code Playgroud)
谢谢
Sad*_*que 10
你不应该对void指针进行指针运算.
来自C标准
6.5.6-2:另外,两个操作数都应具有算术类型,或者一个操作数应为指向对象类型的指针,另一个操作数应为整数类型.
6.2.5-19:void类型包含一组空值; 它是一种不完整的类型,无法完成.
GNU C允许通过考虑voidis 的大小来实现上述目的1.
从6.23关于void-和Function-Pointers的算术:
在GNU C中,指向void的指针和指向函数的指针都支持加法和减法操作.这是通过将空白或函数的大小视为1来完成的.
所以按照以上几行我们得到:
address2 = BlockAddress + 1*size; //increase by 50 Bytes
address3 = BlockAddress + 2*size; //increase by 100 Bytes
Run Code Online (Sandbox Code Playgroud)