将char解析为typedef union数组

时间:2017-10-13 07:38:06

标签: c

我有两个结构的联合,

typedef struct {
    uint8_t ssid[32];      /**< SSID of target AP*/
    uint8_t password[64];  /**< password of target AP*/
    bool bssid_set;        /**< whether set MAC address of target AP or not. Generally, station_config.bssid_set needs to be 0; and it needs to be 1 only when users need to check the MAC address of the AP.*/
    uint8_t bssid[6];     /**< MAC address of target AP*/
    uint8_t channel;       /**< channel of target AP. Set to 1~13 to scan starting from the specified channel before connecting to AP. If the channel of AP is unknown, set it to 0.*/
} wifi_sta_config_t;

typedef union {
    wifi_ap_config_t  ap;  /**< configuration of AP */
    wifi_sta_config_t sta; /**< configuration of STA */
} wifi_config_t;

我正在努力实现这样的目标,

char* ssid = "MYSSID";
char* psw = "MYPSW";

wifi_config_t sta_config = { .sta = { .ssid = {ssid}, .password = {psw}, .bssid_set = 0 } };

我甚至试过这个,但没有运气,

uint8_t ssid[32] = {"MYSSID"};
uint8_t psw[64] = {"MYPSW"};

wifi_config_t sta_config = { .sta = { .ssid = {ssid}, .password = {psw}, .bssid_set = 0 } };

但上面不起作用并给了我warning: initialization makes integer from pointer without a cast

我在这里做错了什么?

任何帮助都会非常感激。

编辑:

结构联合的硬编码值工作正常,

wifi_config_t sta_config = { .sta = { .ssid = {"MYSSID"}, .password = {"MYPSW"}, .bssid_set = 0 } };

上面的代码编译/运行正常,但我想以编程方式更改ssidpassword。我怎样才能做到这一点?

2 个答案:

答案 0 :(得分:0)

问题在于你不能用C中的另一个数组初始化一个数组。这是C中的(奇怪的)语法限制。因此.ssid = {ssid}之类的代码将不起作用。

但是,您可以复制属于结构/联合的数组。非常不一致。因此,要初始化struct / union,您可以使用复合文字来创建struct / union(未测试的代码):

wifi_config_t sta_config = 
  (wifi_config_t) 
  { 
    .sta = 
    { 
      .ssid = "MYSSID", 
      .password = "MYPSW", 
      .bssid_set = 0 
    } 
  };

答案 1 :(得分:0)

我一直在寻找答案,终于找到答案。如前所述,您需要使用strcpy而不是对其进行分配。但是您需要使用强制转换(char *),这是示例

char * myssid = "example";
strcpy((char *)wifi_config.sta.ssid,myssid);