簡體   English   中英

使用數組並集初始化結構

[英]Initializing struct with union of arrays

我注意到有很多關於這個主題的帖子,但我似乎無法指出任何有幫助的內容。

我定義了以下代碼:

typedef struct
{
    float re;
    float im;
} MyComplex;

typedef struct
{
    float rf;
    union
    {
        float     noise[4];
        MyComplex iq[4];
    };
} RfTable_t;

RfTable_t Noise[2] = 
{
    { 1.2f, .noise=0.f },
    { 2.1f, .noise=0.f };
};

**EDIT - Add function Test**

void Test()
{
    Noise[0].rf = 2.1f;
    Noise[0].noise[0] = 3.2f;
}

我正在嘗試靜態定義全局變量Noise 我收到以下錯誤:

   expected primary expression before '{' token
   expected primary expression before '{' token
   expected primary expression before '}' before '{' token
   expected primary expression before '}' before '{' token
   expected primary expression before ',' or ';' before '{' token
   expected declaration before '}' token

要初始化的任何結構、聯合和/或數組都需要自己的一組花括號來初始化它。 具體來說,聯合需要一組大括號,聯合內部的float組也需要大括號:

RfTable_t Noise[2] =
{
    { 1.2f, { .noise={0.f} } },
    { 2.1f, { .noise={0.f} } }
};

還要注意你有一個流浪; 初始化器內部。

我做了最小的更改以使其編譯:

#include <stdio.h>

typedef struct
{
    float re;
    float im;
} MyComplex;

typedef struct
{
    float rf;
    union
    {
        float     noise[4];
        MyComplex iq[4];
    };
} RfTable_t;

RfTable_t Noise[2] = 
{
    { 1.2f, .noise={0.f} },  // Initialize NOISE with {0.f} instead of 0.f.
    { 2.1f, .noise={0.f} }   // Remove extra semi-colon.
};


int main(void) {
    return 0;
}

干凈編譯:

https://ideone.com/pvI9Ci

簡單來說:
noise是一個數組。
要初始化它,您必須使用數組初始值設定項語法:
{ value, value, value }

您的0.f值周圍沒有括號。

此外,您還有一個額外的分號。

暫無
暫無

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

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