gpt4 book ai didi

c - 如何解释 C11 标准的第 6.3.2.3 部分第 7 部分?

转载 作者:行者123 更新时间:2023-12-05 01:30:05 25 4
gpt4 key购买 nike

在另一个 question 的上下文中有一些关于是否允许(即是否会引入实现定义或未定义的行为)将 int** 转换为 void** 并随后分配一个值的讨论到取消引用的 void*。这让我想到了关于 C11 standard 的解释的问题。

6.2.5 (28) A pointer to void shall have the same representation and alignment requirements as a pointer to a character type. ...
6.3.2.3 (1) A pointer to void may be converted to or from a pointer to any object type. A pointer to any object type may be converted to a pointer to void and back again; the result shall compare equal to the original pointer.
6.3.2.3 (7) ... When a pointer to an object is converted to a pointer to a character type, the result points to the lowest addressed byte of the object. ...

我的问题是这是否

int* intptr = NULL;
void* dvoidptr = &intptr; /* 6.3.2.3 (1) */
*(void**)dvoidptr = malloc(sizeof *intptr); /* using 6.3.2.3 (1) */

是否符合标准?这对我来说似乎很奇怪,但我找不到确凿的论据,为什么不呢。 void*void** 由 6.3.2.3 和 6.2.5 以及 6.3.2.3 帮助对齐。

最佳答案

代码无效。

看重点:

6.3.2.3 (1) A pointer to void may be converted to or from a pointer to any object type. A pointer to any object type may be converted to a pointer to void and back again; the result shall compare equal to the original pointer.

您正在将 int** 转换为 void*(正常),然后转换为不同类型的 void**(不正确)。 C 不保证您可以安全地将 void* 转换为原始类型以外的任何类型(除了转换为 char *)

此外,*(void**)dvoidptr 导致 void* 而实际上存在 int*。例如,如果 sizeof(void*) == 2sizeof(int*) == 1 会怎样?您可以转换 void* 指针为其他类型,但不能重新解释它直接为其他类型。

关于c - 如何解释 C11 标准的第 6.3.2.3 部分第 7 部分?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24010608/

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