是否可以在不使用函数的情况下初始化const结构?

时间:2008-10-13 20:44:27

标签: c

我在一些C代码中有一个相当简单的const结构,它只包含几个指针,并希望在可能的情况下静态初始化它。我可以,如果是,如何?

4 个答案:

答案 0 :(得分:15)

如果指针指向全局对象,则可以:

// In global scope
int x, y;
const struct {int *px, *py; } s = {&x, &y};

答案 1 :(得分:5)

const struct mytype  foo = {&var1, &var2};

答案 2 :(得分:1)

const结构只能 静态初始化。

答案 3 :(得分:0)

但如果有struct如下:

struct Foo
{
    const int a;
    int b;
};

我们希望使用struct动态创建指向malloc的指针,因此我们可以发挥作用:

struct Foo foo = { 10, 20 };
char *ptr = (char*)malloc(sizeof(struct Foo));
memcpy(ptr, &foo, sizeof(foo));
struct Foo *pfoo = (struct Foo*)ptr;

这非常有用,尤其是当某些函数需要返回指向struct Foo

的指针时
相关问题