본문 바로가기

C

[C언어] 구조체 안에서 다른 구조체를 멤버 변수로 가질 수 있다.

반응형

구조체 안에서 다른 구조체를 멤버 변수로 가질 수 있다.


#include<stdio.h>
#include<string.h>   // strlen(), strcpy()

struct profile{
   int age;
   double height;
   char* name;          // 동적할당을 위한 포인터 변수를 선언한다.
};

struct student{
   struct profile pf;   // 다른 구조체를 멤버로 가진다.
   int id;
   double grade;
};

int main(){

   struct student stu;
   char tmp_name[10];   // (필수) 동적할당을 위해 임의의 변수를 선언해준다.

   printf("이름 입력 : ");
   scanf("%s", tmp_name);
   stu.pf.name = (char*)malloc(strlen(tmp_name) + 1);   // tmp_name의 문자열 길이('\0' 이전까지의 길이)에 1을 더해준다.
   strcpy(stu.pf.name, tmp_name);

   printf("이름  : %s\n", stu.pf.name);
   //printf("나이  : %d\n", stu.pf.age);
   //printf("키    : %.2lf\n", stu.pf.height);
   //printf("id    : %d\n", stu.id);
   //printf("grade : %.2lf\n", stu.grade);

   free(stu.pf.name);

   return 0;
}

 

반응형