POST

C언어 구조체 변수의 초기화

int 형 변수를 선언과 동시에 초기화할 수 있듯이 구조체 변수도 선언과 동시에 초기화할 수 있다.

그리고 구조체 변수의 초기화는 배열의 초기화와 유사하다. 즉 멤버의 순서대로 초기화할 대상을 나열하면 된다.


아래의 코드를 살펴보자.


#include<stdio.h>

struct point {

int xpos;

int ypos;

};


struct person {

char name[20];

char phoneNum[20];

int age;

};


int main(void) {

struct point pos = { 10, 20 }; // 선언과 초기화

struct person man = { "GD", "010-1234-5678", 22 }; // 선언과 초기화

printf("%d %d \n", pos.xpos, pos.ypos);

printf("%s %s %d \n", man.name, man.phoneNum, man.age);

return 0;

}