簡體   English   中英

結構內的聯合。 編譯警告。 C

[英]union within struct. compilation warnings. c

我有休閑結構:

struct lshort_sched_param {
    int requested_time;
    int level;
};

struct sched_param {
    union {
        int sched_priority;
        struct lshort_sched_param lshort_params;
    };
};

我正在嘗試創建它們的新實例,如下所示:

struct lshort_sched_param *l = {2 ,1};
struct sched_param *p = {3, l}; 

並得到一些警告:

test.c:5: warning: initialization makes pointer from integer without a cast
test.c:5: warning: excess elements in scalar initializer
test.c:5: warning: (near initialization for `l')
test.c:6: warning: initialization makes pointer from integer without a cast
test.c:6: warning: excess elements in scalar initializer
test.c:6: warning: (near initialization for `p')

誰能幫我解決這個問題?

這是不允許的:

struct lshort_sched_param *l = {2 ,1};

用括號括起來的初始化程序列表包含多個元素只能初始化struct或數組,而不能初始化指針。

您可以這樣寫:

struct lshort_sched_param m = { 2, 1 };
struct lshort_sched_param *ptr_m = &m;     // optional

您還需要考慮m的存儲持續時間。 (注意。我使用m而不是l作為變量名,因為在許多字體中后者看起來像1 )。

另一種可能性是:

struct lshort_sched_param *ptr_m = (struct lshort_sched_param) { 2, 1 };

在這種情況下,您可以修改ptr_m指向的對象。 這稱為復合文字 如果ptr_m這樣做,它將具有自動存儲持續時間(“在堆棧上”); 否則,它具有靜態存儲期限。


struct sched_param *p = {3, l};情況變得更糟struct sched_param *p = {3, l}; 然而。 同樣,初始化程序無法初始化指針。

同樣,聯合初始化器只能有一個元素。 不允許嘗試初始化一個聯盟中的多個成員。 無論如何,這沒有任何意義。 (也許您誤解了工會的工作方式)。

另一個可能的問題是,文件范圍內的初始化程序必須是常量表達式。

您在聲明指針,但是在嘗試修改它們所指向的東西之前,它們必須指向一些東西,可以使用malloc這樣完成。

struct lshort_sched_param *l = NULL;
l = malloc(sizeof(struct lshort_sched_param));

struct sched_param *p = NULL;
p = malloc(sizeof(struct sched_param));

我們在做什么?。 好吧,malloc在內存上分配了一些字節,並返回了一個指向塊開頭的指針,在本例中,我們將malloc返回的指針分配給了指針l和p,結果是現在l和p指向了指針。我們剛剛制作的結構。

然后,您可以通過這種方式更改由p和l指向的結構的值。

l->requested_time = 2;
l->level = 1;
p->sched_priority = 3;
p->lshort_params.requested_time = 1;
p->lshort_params.level = 1;

編輯:

顯然,您也可以這樣做。

struct lshort_sched_param p = {2, 1};

接着。

struct lshort_sched_param *ptr = &p;

但是當你做的時候。

struct lshort_sched_param *l;

您只是在聲明一個指針,僅此而已,它直到指向變量的地址才指向任何東西。

我認為您想執行以下操作:

struct lshort_sched_param {
    int requested_time;
    int level;
};

union sched_param {
    int sched_priority;
    struct lshort_sched_param lshort_params;
};

要為struct / union分配內存,請執行以下操作:

struct lshort_sched_param l = {2 ,1};
union sched_param p;
// init
// either this
p.sched_priority = 3;
// or that
p.lshort_params = l;

您的行struct sched_param *p = {3, l}; 沒有道理。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM