繁体   English   中英

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

[英]Is it possible to initialize a const struct without using a function?

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

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

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

const结构只能静态初始化。

但如果有一些struct如下:

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

我们想使用malloc动态创建指向struct的指针,所以我们可以玩这个技巧:

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指针时

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM