Programing

C의 구조체 멤버에 대한 기본값

lottogame 2020. 11. 21. 08:18
반응형

C의 구조체 멤버에 대한 기본값


일부 구조체 멤버의 기본값을 설정할 수 있습니까? 다음을 시도했지만 구문 오류가 발생했습니다.

typedef struct
{
  int flag = 3;
} MyStruct;

오류 :

$ gcc -o testIt test.c 
test.c:7: error: expected ‘:’, ‘,’, ‘;’, ‘}’ or ‘__attribute__’ before ‘=’ token
test.c: In function ‘main’:
test.c:17: error: ‘struct <anonymous>’ has no member named ‘flag’

구조는 데이터 유형 입니다. 데이터 유형에 값을 제공하지 않습니다. 데이터 유형의 인스턴스 / 객체에 값을 제공합니다.
따라서 C에서는 불가능합니다.

대신 구조 인스턴스에 대한 초기화를 수행하는 함수를 작성할 수 있습니다.

또는 다음을 수행 할 수 있습니다.

struct MyStruct_s 
{
    int id;
} MyStruct_default = {3};

typedef struct MyStruct_s MyStruct;

그런 다음 항상 새 인스턴스를 다음과 같이 초기화하십시오.

MyStruct mInstance = MyStruct_default;

C에서 구조를 정의 할 때 초기화 할 수 없다는 Als에 동의합니다. 그러나 아래와 같이 인스턴스 생성시 구조를 초기화 할 수 있습니다.

C에서는

 struct s {
        int i;
        int j;
    };

    struct s s_instance = { 10 ,20 };

C ++에서는 아래와 같이 구조 정의에 직접적인 가치를 부여 할 수 있습니다.

struct s {
    int i;

    s(): i(10)
    {
    }
};

다음과 같이 일부 함수를 사용하여 구조체를 초기화 할 수 있습니다.

typedef struct
{
    int flag;
} MyStruct;

MyStruct GetMyStruct(int value)
{
    MyStruct My = {0};
    My.flag = value;
    return My;
}

void main (void)
{
    MyStruct temp;
    temp = GetMyStruct(3);
    printf("%d\n", temp.flag);
}

편집하다:

typedef struct
{
    int flag;
} MyStruct;

MyStruct MyData[20];

MyStruct GetMyStruct(int value)
{
    MyStruct My = {0};
    My.flag = value;
    return My;
}

void main (void)
{
    int i;
    for (i = 0; i < 20; i ++)
        MyData[i] = GetMyStruct(3);

    for (i = 0; i < 20; i ++)
        printf("%d\n", MyData[i].flag);
}

Create a default struct as the other answers have mentioned:

struct MyStruct
{
    int flag;
}

MyStruct_default = {3};

However, the above code will not work in a header file - you will get error: multiple definition of 'MyStruct_default'. To solve this problem, use extern instead in the header file:

struct MyStruct
{
    int flag;
};

extern const struct MyStruct MyStruct_default;

And in the c file:

const struct MyStruct MyStruct_default = {3};

Hope this helps anyone having trouble with the header file.


An initialization function to a struct is a good way to grant it default values:

Mystruct s;
Mystruct_init(&s);

Or even shorter:

Mystruct s = Mystruct_init();  // this time init returns a struct

Another approach to default values. Make an initialization function with the same type as the struct. This approach is very useful when splitting large code into separate files.

struct structType{
  int flag;
};

struct structType InitializeMyStruct(){
    struct structType structInitialized;
    structInitialized.flag = 3;
    return(structInitialized); 
};


int main(){
    struct structType MyStruct = InitializeMyStruct();
};

참고URL : https://stackoverflow.com/questions/13716913/default-value-for-struct-member-in-c

반응형