C에서 구조체 초기화

Jinku Hu 2023년10월12일 C C Struct
  1. 이니셜 라이저 목록 스타일 표기법을 사용하여 C에서 구조체 초기화
  2. 할당 목록 표기법을 사용하여 C에서 구조체 초기화
  3. 개별 할당을 사용하여 C에서 구조체 초기화
C에서 구조체 초기화

이 기사에서는 C에서 구조체를 초기화하는 방법에 대한 여러 메서드를 소개합니다.

이니셜 라이저 목록 스타일 표기법을 사용하여 C에서 구조체 초기화

struct는 아마도 C에서 복잡한 데이터 구조를 구축하는 데 가장 중요한 키워드 일 것입니다.members라고하는 여러 이기종 요소를 저장할 수있는 내장 객체입니다.

구조체는struct 키워드로만 정의되지만 다음 예제에서는typedef를 추가하여 새 유형 이름을 만들고 후속 선언을 더 읽기 쉽게 만듭니다.

구조가 정의되면이 유형의 변수를 선언하고 목록 표기법으로 초기화 할 수 있습니다. 이 구문은 C++에서 사용되는 이니셜 라이저 목록과 유사합니다. 이 경우 struct의 각 멤버에 명시 적 할당 연산자를 할당하지만 올바른 순서로만 값을 지정할 수 있으며 최신 버전의 언어에서는 충분합니다.

#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef struct Person {
  char firstname[40];
  char lastname[40];
  int age;
  bool alive;
} Person;

int main(void) {
  Person me = {
      .firstname = "John\0", .lastname = "McCarthy\0", .age = 24, .alive = 1};

  printf("Name: %s\nLast Name: %s\nAge: %d\nAlive: ", me.firstname, me.lastname,
         me.age);
  me.alive ? printf("Yes\n") : printf("No\n");

  exit(EXIT_SUCCESS);
}

출력:

Name: John
Last Name: McCarthy
Age: 24
Alive: Yes

할당 목록 표기법을 사용하여 C에서 구조체 초기화

또는 선언 된struct가 즉시 초기화되지 않고 나중에 프로그램에서 값을 할당해야하는 시나리오가있을 수 있습니다. 이 경우 추가 캐스트 표기법을 접두사로 사용하는 이니셜 라이저 목록 스타일 구문을 사용해야합니다. struct 유형으로의 캐스팅은 프로그램을 컴파일하는 데 필요한 단계입니다.

#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef struct Person {
  char firstname[40];
  char lastname[40];
  int age;
  bool alive;
} Person;

int main(void) {
  Person me;

  me = (Person){
      .firstname = "John\0", .lastname = "McCarthy\0", .age = 24, .alive = 1};

  printf("Name: %s\nLast Name: %s\nAge: %d\nAlive: ", me.firstname, me.lastname,
         me.age);
  me.alive ? printf("Yes\n") : printf("No\n");

  exit(EXIT_SUCCESS);
}

출력:

Name: John
Last Name: McCarthy
Age: 24
Alive: Yes

개별 할당을 사용하여 C에서 구조체 초기화

struct 멤버를 초기화하는 또 다른 방법은 변수를 선언 한 다음 각 멤버에 해당 값을 개별적으로 할당하는 것입니다. char 배열은 문자열로 할당 할 수 없으므로memcpy 또는memmove와 같은 추가 기능을 사용하여 명시 적으로 복사해야합니다(수동). 항상 배열의 길이가 저장되는 문자열보다 작아서는 안된다는 점에 유의해야합니다.

#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef struct Person {
  char firstname[40];
  char lastname[40];
  int age;
  bool alive;
} Person;

int main(void) {
  Person me2;

  memcpy(&me2.firstname, "Jane\0", 40);
  memcpy(&me2.lastname, "Delaney\0", 40);
  me2.age = 27;
  me2.alive = true;

  printf("Name: %s\nLast Name: %s\nAge: %d\nAlive: ", me2.firstname,
         me2.lastname, me2.age);
  me2.alive ? printf("Yes\n") : printf("No\n");

  exit(EXIT_SUCCESS);
}

출력:

Name: Jane
Last Name: Delaney
Age: 27
Alive: Yes
튜토리얼이 마음에 드시나요? DelftStack을 구독하세요 YouTube에서 저희가 더 많은 고품질 비디오 가이드를 제작할 수 있도록 지원해주세요. 구독하다
작가: Jinku Hu
Jinku Hu avatar Jinku Hu avatar

Founder of DelftStack.com. Jinku has worked in the robotics and automotive industries for over 8 years. He sharpened his coding skills when he needed to do the automatic testing, data collection from remote servers and report creation from the endurance test. He is from an electrical/electronics engineering background but has expanded his interest to embedded electronics, embedded programming and front-/back-end programming.

LinkedIn Facebook

관련 문장 - C Struct