programing

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

lovejava 2023. 8. 27. 08:48

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;

당신은 이런 식으로 그것을 할 수 없습니다.

대신 다음을 사용합니다.

typedef struct
{
   int id;
   char* name;
}employee;

employee emp = {
.id = 0, 
.name = "none"
};

매크로를 사용하여 인스턴스를 정의하고 초기화할 수 있습니다.이렇게 하면 새 인스턴스를 정의하고 초기화할 때마다 쉽게 실행할 수 있습니다.

typedef struct
{
   int id;
   char* name;
}employee;

#define INIT_EMPLOYEE(X) employee X = {.id = 0, .name ="none"}

코드에서 직원 유형으로 새 인스턴스를 정의해야 하는 경우 이 매크로를 다음과 같이 부릅니다.

INIT_EMPLOYEE(emp);

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

주식회사,

struct s {
    int i;
    int j;
};

struct s s_instance = { 10, 20 };

C++에서 아래와 같이 구조의 정의에 직접적인 값을 주는 것이 가능합니다.

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

할 수 있는 일:

struct employee_s {
  int id;
  char* name;
} employee_default = {0, "none"};

typedef struct employee_s employee;

그런 다음 새 직원 변수를 선언할 때 기본 초기화를 수행해야 합니다.

employee foo = employee_default;

또는 언제든지 공장 기능을 통해 직원 구조를 구축할 수 있습니다.

다른 답변에서 언급한 대로 기본 구조를 만듭니다.

struct MyStruct
{
    int flag;
}

MyStruct_default = {3};

그러나 위의 코드는 헤더 파일에서 작동하지 않습니다. 오류가 발생합니다.multiple definition of 'MyStruct_default'이 문제를 해결하려면 다음을 사용합니다.extern대신 헤더 파일:

struct MyStruct
{
    int flag;
};

extern const struct MyStruct MyStruct_default;

그리고.c파일:

const struct MyStruct MyStruct_default = {3};

이것이 헤더 파일에 문제가 있는 사람들에게 도움이 되기를 바랍니다.

사용 중인 경우gcc줄 수 있습니다designated initializers개체 생성 중입니다.

typedef struct {
    int id = 0;
    char *name = "none";
} employee;

employee e = {
    .id = 0;
    .name = "none";
};

또는 배열 초기화와 같이 사용합니다.

employee e = {0 , "none"};

더 나아가 기존 응답에 추가하기 위해 구조체 이니셜라이저를 숨기는 매크로를 사용할 수 있습니다.

#define DEFAULT_EMPLOYEE { 0, "none" }

그러면 코드에서:

employee john = DEFAULT_EMPLOYEE;

초기화 기능을 구현할 수 있습니다.

employee init_employee() {
  empolyee const e = {0,"none"};
  return e;
}

C 전처리기 함수를 변수, 복합 리터럴 및 지정된 이니셜라이저와 함께 사용하여 최대 편의성을 얻을 수 있습니다.

typedef struct {
    int id;
    char* name;
} employee;

#define EMPLOYEE(...) ((employee) { .id = 0, .name = "none", ##__VA_ARGS__ })

employee john = EMPLOYEE(.name="John");  // no id initialization
employee jane = EMPLOYEE(.id=5);         // no name initialization

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

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);
}

이 구조를 한 만 사용하는 경우(즉, 전역/정적 변수를 만드는 경우) 제거할 수 있습니다.typedef그리고 이 변수를 즉시 초기화했습니다.

struct {
    int id;
    char *name;
} employee = {
    .id = 0,
    .name = "none"
};

그런 다음 사용할 수 있습니다.employee그 후에 당신의 코드에.

구조가 허용하는 경우 내부의 기본값을 사용하여 #define을 사용하는 방법도 있습니다.

#define MYSTRUCT_INIT { 0, 0, true }

typedef struct
{
    int id;
    int flag;
    bool foo;
} MyStruct;

사용:

MyStruct val = MYSTRUCT_INIT;

구조체에 대한 초기화 함수는 기본값을 부여하는 좋은 방법입니다.

Mystruct s;
Mystruct_init(&s);

또는 더 짧습니다.

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

기본값에 대한 또 다른 접근 방식입니다.구조체와 동일한 유형으로 초기화 함수를 만듭니다.이 방법은 큰 코드를 별도의 파일로 분할할 때 매우 유용합니다.

struct structType{
  int flag;
};

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


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

다음과 같은 기능을 만들 수 있습니다.

typedef struct {
    int id;
    char name;
} employee;

void set_iv(employee *em);

int main(){
    employee em0; set_iv(&em0);
}

void set_iv(employee *em){
    (*em).id = 0;
    (*em).name = "none";
}

저는 당신이 다음과 같은 방법으로 할 수 있다고 생각합니다.

typedef struct
{
  int flag : 3;
} MyStruct;

언급URL : https://stackoverflow.com/questions/13706809/structs-in-c-with-initial-values