![](/img/trans.png)
[英]Is there a way to initialize a `const` `struct` using `const` variables?
[英]Is it possible to initialize a const struct without using a function?
我在一些C代碼中有一個相當簡單的const結構,它只包含幾個指針,並希望在可能的情況下靜態初始化它。 我可以,如果是這樣,怎么樣?
如果指針指向全局對象,則可以:
// In global scope
int x, y;
const struct {int *px, *py; } s = {&x, &y};
const struct mytype foo = {&var1, &var2};
const結構只能靜態初始化。
但如果有一些struct
如下:
struct Foo
{
const int a;
int b;
};
我們想使用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;
這非常有用,尤其是當某些函數需要返回指向struct Foo
指針時
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.