简体   繁体   中英

Warning with struct initialization

I have this struct:

struct ChangeIntItem
{
    char *unit;
    const char **parser;
    int *changevalue;
    uint16_t *change_eeprom_value;
    int maximum;
    int minimum;
};

I want to initialize other variables with this struct-Variable:

struct ChangeIntItem ChangeIntItemTypeBoolean = { .unit = "", .minimum = 0, .maximum = 1, .parser = {"off", "on"}};

It is working fine but I get some warnings:

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

In another case I wrote a function which sets the variables of the struct to default-values but I prefer this method because its much shorter.

All mistakes where caused by '.parser = {"off", "on"}' but I don't get my mistake...

You can use compound literals , so change init to

struct ChangeIntItem ChangeIntItemTypeBoolean = { .unit = "", .minimum = 0, .maximum = 1, .parser = (const char *[]){"off", "on"}};

Test

#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]);
}

Output

off - on

Member parser is a pointer.

Change it to an array of pointers, so the initialization can be kept the same:

 const char *parser[2];

Or use a compound literal or another variable:

.parser = ( const char*[]){"off", "on"}

const char* array[2] = {"off", "on"};
.parser = array

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM