我有这个结构:
struct ChangeIntItem
{
char *unit;
const char **parser;
int *changevalue;
uint16_t *change_eeprom_value;
int maximum;
int minimum;
};
我想用这个struct-Variable初始化其他变量:
struct ChangeIntItem ChangeIntItemTypeBoolean = { .unit = "", .minimum = 0, .maximum = 1, .parser = {"off", "on"}};
工作正常,但我收到一些警告:
Severity Code Description Project File Line
Warning braces around scalar initializer Handsteuerung C:\Users\... 11
Severity Code Description Project File Line
Warning (near initialization for 'ChangeIntItemTypeBoolean.parser') Handsteuerung C:\Users\... 11
Severity Code Description Project File Line
Warning initialization from incompatible pointer type Handsteuerung C:\Users\... 11
Severity Code Description Project File Line
Warning (near initialization for 'ChangeIntItemTypeBoolean.parser') Handsteuerung C:\Users\... 11
Severity Code Description Project File Line
Warning excess elements in scalar initializer Handsteuerung C:\Users\... 11
Severity Code Description Project File Line
Warning (near initialization for 'ChangeIntItemTypeBoolean.parser') Handsteuerung C:\Users\... 11
在另一个案例中,我写了一个函数,它将struct的变量设置为default-values,但我更喜欢这个方法,因为它更短。
由' .parser = {" off"," on"}'引起的所有错误但我没有弄错...
答案 0 :(得分:5)
您可以使用compound literals,因此请将init更改为
struct ChangeIntItem ChangeIntItemTypeBoolean = { .unit = "", .minimum = 0, .maximum = 1, .parser = (const char *[]){"off", "on"}};
测试
#include <stdio.h>
#include <stdint.h>
struct ChangeIntItem
{
char *unit;
const char **parser;
int *changevalue;
uint16_t *change_eeprom_value;
int maximum;
int minimum;
};
int main()
{
struct ChangeIntItem ChangeIntItemTypeBoolean = { .unit = "", .minimum = 0, .maximum = 1, .parser = (const char *[]){"off", "on"}};
printf ("%s - %s\n", ChangeIntItemTypeBoolean.parser[0], ChangeIntItemTypeBoolean.parser[1]);
}
输出
off - on
答案 1 :(得分:4)
成员parser
是一个指针。
将其更改为指针数组,因此初始化可以保持不变:
const char *parser[2];
或使用复合文字或其他变量:
.parser = ( const char*[]){"off", "on"}
const char* array[2] = {"off", "on"};
.parser = array