结构体定义,初始化和赋值

文件:funcB.c直接上代码:

#include "stdio.h"


struct NODE{


    int value;

    struct NODE *nextNode;

    struct NODE *preNode;

    

};


typedef struct NODE sNODE;


sNODE NodeBrightness;

sNODE NodeContrast;

sNODE NodeSharp;


int main()

{

printf("main\n");


    NodeContrast = {30, NULL, NULL};

    NodeSharp = {70, NULL, NULL};

    NodeBrightness = {50, &NodeContrast, NULL};

    

//    NodeBrightness.nextNode = &NodeContrast;


    NodeContrast.nextNode = &NodeSharp;

    NodeContrast.preNode = &NodeBrightness;

    

    NodeSharp.preNode = &NodeContrast;

    

//    NodeBrightness = {50, &NodeContrast, NULL};

//    NodeContrast = {30, &NodeSharp, NodeBrightness};

//    NodeBrightness = {70, NULL, NodeContrast};

    

    printf("Brightness = %d\n", NodeBrightness.value);

    printf("Contrast = %d\n", NodeContrast.value);

    printf("Sharpness = %d\n", NodeSharp.value);


    printf("Brightness next value = %d\n", NodeBrightness.nextNode->value);


    printf("Contrast next value = %d\n", NodeContrast.nextNode->value);


    printf("Sharpness pre value = %d\n", NodeSharp.preNode->value);

    

    return 0;


}

编译:

gcc -o NextNode funcB.c

错误:

funcB.c:21:20: error: expected expression

    NodeContrast = {30, NULL, NULL};

                   ^

funcB.c:22:17: error: expected expression

    NodeSharp = {70, NULL, NULL};

                ^

funcB.c:23:22: error: expected expression

    NodeBrightness = {50, &NodeContrast, NULL};

                     ^

3 errors generated.

原因:一个结构体对象不能初始化两次,实际上在定义 sNODE NodeBrightness;的时候就已经对其初始化为{0, NULL, NULL},再次用语句:

    NodeBrightness = {50, &NodeContrast, NULL};

对其初始化为 { 50 , &NodeContrast,  NULL }会报错。

但是可以对其单独赋值,比如:

    NodeBrightness.value = 50;

    NodeBrightness.nextNode = &NodeContrast;

再次编译,没有报错,运行:
./NextNode

main

Brightness = 50

Contrast = 0

Sharpness = 0

Brightness next value = 0

Contrast next value = 0

Sharpness pre value = 0


在这里可以看到,contrast节点和sharpness节点全部为0(默认初始化为0)。





你可能感兴趣的:(编译,C语法,LINUX)