ant2009
ant2009

Reputation: 22666

Initializing a structure

gcc 4.5.1 c89

compiling with the following flags: -Wall, -Wextra

I have the following structure that I am trying to initialize with default values. However, I get the following warnings:

static struct Device {
    char *name;
    char *config;
} *app = { NULL, NULL };

Warnings:

warning: initialization from incompatible pointer type
warning: excess elements in scalar initializer

However, if I do the following by declaring a non-pointer, I don't get any problems i.e.

 static struct Device {
        char *name;
        char *config;
    } app = { NULL, NULL };

Why is that?

Many thanks for any advice,

Upvotes: 0

Views: 384

Answers (3)

AndersK
AndersK

Reputation: 36092

because *app is a pointer so initializing it to { NULL, NULL } is wrong, you should initialize it to simply NULL.

in the case of app you have an actual variable instance of the struct so there you initialize the members of the struct to NULL, that is OK.

Upvotes: 2

icecrime
icecrime

Reputation: 76835

A pointer is not a structure but a simple type whose value is an address.

  • If your app variable is of pointer type, it may be initialized with NULL but not with the braces syntax you use
  • If the app variable is of type struct Device, you may use the brace initializer to provide an initial NULL value to the name and config fields

Upvotes: 2

Pablo Santa Cruz
Pablo Santa Cruz

Reputation: 181460

You can't initialize a pointer that way. You can do this though:

static struct Device {
    char *name;
    char *config;
} *app = NULL;

Initialize a pointer to NULL. A pointer is nothing but a memory address. You can't assing { NULL, NULL } to a memory address.

Upvotes: 2

Related Questions