結構體定義,初始化和賦值

文件: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)。





發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章