quikchange
quikchange

Reputation: 554

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?

Upvotes: 12

Views: 14631

Answers (4)

ylzhang
ylzhang

Reputation: 1108

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

Upvotes: 0

Frank Szczerba
Frank Szczerba

Reputation: 5060

A const struct can only be initialized statically.

Upvotes: 2

AShelly
AShelly

Reputation: 35540

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

Upvotes: 5

Lev
Lev

Reputation: 6657

You can, if the pointers point to global objects:

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

Upvotes: 15

Related Questions