tags:

views:

2467

answers:

4

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?

+6  A: 

You can, if the pointers point to global objects:

// In global scope
int x, y;
const struct {int *px, *py; } s = {&x, &y};
Lev
+1  A: 
const struct mytype  foo = {&var1, &var2};
AShelly
A: 

A const struct can only be initialized statically.

Frank Szczerba
A: 

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

Emacs