[英]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. 我在一些C代码中有一个相当简单的const结构,它只包含几个指针,并希望在可能的情况下静态初始化它。 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
如下:
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: 我们想使用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;
this is very useful especially when some function needs to return pointer to struct Foo
这非常有用,尤其是当某些函数需要返回指向struct Foo
指针时
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.