본문 바로가기
프로그램/C언어 1000제

C언어 126제] C언어 콘서트 CHAPTER 13 Programming 6 동적메모리를 활용하여 성적을 나타내는 구조체 프로그래 작성하기. p511

by 건티 2022. 2. 8.
728x90

 

 

참고풀이]

#include <stdio.h>
#include <stdlib.h> //malloc(), free(), exit()

struct course{
   char subject[30];//과목 이름 
   double marks;//학점 
};

int main()
{
   int N;//구조체의 개수 입력변수
   struct course *M;//구조체의 개수에 해당하는 동적메모리 변수 
   int i;//반복변수 

   //구조체의 개수 입력
   printf("구조체의 개수 : "); scanf("%d",&N);

   //동적메모리를 할당한다.
   M=(struct course *)malloc(sizeof(struct course *)*N);

   if(M==NULL)
   {
      printf("메모리 할당 오류\n");
      exit(1);
   }

   //할당된 동적메모리에 과목과 학점을 넣는다.
   for(i=0;i<N;i++)
   {
      printf("과목의 이름과 성적을 입력하시오 : ");
      scanf("%s%lf",&M[i].subject, &M[i].marks);
   }

   //결과출력
   printf("저장된 정보 출력:\n");
   for(i=0;i<N;i++)
      printf("%-10s %lf\n",M[i].subject, M[i].marks);

   //할당한 동적메모리 해제
   free(M);

   return 0;
}

 

참고풀이 결과]

 

 

 

 

대한민국의 아름다운 영토, 독도의 겨울

 

 

반응형

댓글