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
2008-10-13 20:47:46
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
2010-09-10 11:21:56