c - 通用写入结构指针

标签 c language-lawyer

6.2.5p28 :

A pointer to void shall have the same representation and alignment requirements as a pointer to a character type.48) Similarly, pointers to qualified or unqualified versions of compatible types shall have the same representation and alignment requirements. All pointers to structure types shall have the same representation and alignment requirements as each other. All pointers to union types shall have the same representation and alignment requirements as each other. Pointers to other types need not have the same representation or alignment requirements.

这是否意味着我可以像这样一般地写入一个结构指针:

struct a_struct;

int 
alloc_struct(struct a_struct **X, size_t Sz)
{
    if ((*X=malloc(Sz))) 
        return 0;
    return -ENOMEM;
}

struct foo{ int x; char buf[32]; };;

int main()
{
    struct foo *foo_p;
    alloc_struct((struct a_struct**)&foo_p, sizeof(*foo_p));
}

最佳答案

因为支持各种别名的成本在平台之间可能有很大差异( float 和整数之间的别名特别昂贵),并且因为不同类型的应用程序对别名有不同的需求,所以 C89 标准的作者没有努力描述针对任何特定平台或应用程序领域的实现应支持的所有形式。现有的实现已经在有用的情况下支持别名,标准的作者没有理由期望他们停止。

没有理由不能支持高质量的实现 构造如您描述的构造,尤其是在编译器 将能够在函数调用中看到对 struct a_struct** 的转换,并且指针的目标只能通过 struct a_struct** 访问,但一些实现者查看标准的未能强制支持此类结构意味着判断支持此类结构没有好处。

因此,有两种方法可以实现您寻求的语义:(1) 通过读写单个字符来操作指针(在某些情况下,有效类型会使 memcpy/memmove 不安全),或 (2) 禁用基于类型的别名,并在适当的地方添加 restrict 限定符,使代码比启用基于类型的别名时更高效。

关于c - 通用写入结构指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42307267/

相关文章:

C-堆栈变量在迭代之间消失

c - C的流中字符的含义

c++ - 可以使用 realloc 安全地重新分配普通可复制对象的存储吗?

c - 不知道长度的二维全局数组。最佳实践?

c - 如何将一个整数分成多个数字?

c++ - 多重继承使私有(private)成员可访问

c++ - 空参数包扩展不同于手动空参数包

c++ - 该计划是否违反 ODR?

C - 从最后一行读取文件问题

c - 为什么子进程管道显示在具有不同管道详细信息的父进程中