programing

C의 구조 부재 기본값

prostudy 2022. 7. 26. 22:11
반응형

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에서는 이것이 가능하지 않습니다.

대신 구조 인스턴스(instance)를 초기화하는 함수를 작성할 수 있습니다.

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

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

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

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

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

다음 작업을 수행할 수 있습니다.

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

typedef struct employee_s employee;

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

employee foo = employee_default;

또는 공장 기능을 통해 항상 직원 구조를 구축할 수도 있습니다.

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

주식회사,

 struct s {
        int i;
        int j;
    };

    struct s s_instance = { 10 ,20 };

C++에서는 다음과 같은 구조의 정의에 직접 값을 부여하는 것이 가능하다.

struct s {
    int i;

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

또한 기존 답변을 추가하려면 구조 이니셜라이저를 숨기는 매크로를 사용할 수 있습니다.

#define DEFAULT_EMPLOYEE { 0, "none" }

그러면 코드:

employee john = DEFAULT_EMPLOYEE;

구조가 허용하는 경우 다음 기본값이 포함된 #define을 사용하는 방법도 있습니다.

#define MYSTRUCT_INIT { 0, 0, true }

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

용도:

MyStruct val = MYSTRUCT_INIT;

사용하시는 경우gcc줄 수 있다designated initializers오브젝트 작성에 사용됩니다.

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

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

또는 어레이 초기화처럼 사용합니다.

employee e = {0 , "none"};

이 구조를 한 만 사용하는 경우(즉, 글로벌 변수/정적 변수 생성)에는typedef이 변수를 즉시 초기화했습니다.

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

그 다음에, 을 사용할 수 있습니다.employee코드를 입력해 주세요.

C 프리프로세서 기능을 varargs, 복합 리터럴지정 이니셜라이저와 조합하여 사용하면 편리합니다.

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

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

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

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

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 flag : 3;
} MyStruct;

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

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

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

반응형