c - 指向静态分配结构的全局指针

标签 c pointers struct

我想要一个指向静态分配结构的全局指针。

这个编译

struct sa{
    int a, b;
    char const* c;
};
struct sa* sap = &(struct sa){42,43,"x"};

但它是合法且可移植的 C,还是我必须做类似的事情?:

static struct sa x = {42,43,"x"};
struct sa* sap2  = &x;

最佳答案

显然,根据 http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1570.pdf , 6.5.2.5 复合文字, 5:

The value of the compound literal is that of an unnamed object initialized by the initializer list. If the compound literal occurs outside the body of a function, the object has static storage duration; otherwise, it has automatic storage duration associated with the enclosing block.

在全局范围内使用是合法的。

谢谢 WhozCraig让我知道构造的名称,以便我可以查找它。 ;)

关于c - 指向静态分配结构的全局指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39430200/

相关文章:

c# - 从 C# 调用非托管代码

c - C中的链表数组

c++ - C++ 中的循环指针

c++ - 性能比较整数多维数组与结构数组

c - 动态库文件的全局变量加载到哪里了?

c函数返回静态变量

c - fgets - 数组与指针之间的区别

c++ - 如何将整个结构传递给包含所有元素的函数?

pointers - Go结构指针不是唯一的

c - 用文件中的数据填充结构