开发者

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;
    } ap开发者_如何转开发p = { NULL, NULL };

Why is that?

Many thanks for any advice,


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.


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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜