gpt4 book ai didi

c - 编译器是否应该对带有 void 指针的指针算法发出警告?

转载 作者:太空狗 更新时间:2023-10-29 17:15:33 25 4
gpt4 key购买 nike

我正在使用 gcc 4.7.2 编译 C 程序。我有一个 void * 类型的地址和一些偏移量。 (void* + 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;

谢谢

最佳答案

你不应该对 void 指针进行指针运算。

来自 C 标准

6.5.6-2: For addition, either both operands shall have arithmetic type, or one operand shall be a pointer to an object type and the other shall have integer type.

6.2.5-19: The void type comprises an empty set of values; it is an incomplete type that cannot be completed.

GNU C 通过考虑 void 的大小为 1 来允许上述操作。

来自 6.23 Arithmetic on void- and Function-Pointers :

In GNU C, addition and subtraction operations are supported on pointers to void and on pointers to functions. This is done by treating the size of a void or of a function as 1.

所以按照上面的几行我们得到:

 address2             = BlockAddress + 1*size; //increase by 50 Bytes
address3 = BlockAddress + 2*size; //increase by 100 Bytes

关于c - 编译器是否应该对带有 void 指针的指针算法发出警告?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20967868/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com