简体   繁体   中英

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

I have a fairly simple const struct in some C code that simply holds a few pointers and would like to initialize it statically if possible. Can I and, if so, how?

You can, if the pointers point to global objects:

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

const结构只能静态初始化。

But if there is some struct as following:

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

and we want to dynamically create the pointer to the struct using malloc , so can we play the trick:

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

this is very useful especially when some function needs to return pointer to struct Foo

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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