1. 동적배열을 한번에 받아서 처리

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

struct book{
char name[20];
char title[20];
int page;
};

int main(){
struct book *book1 = (struct book *)malloc(sizeof(struct book)*3); // 구조체 3개 동적할당
int i;

for(i=0; i<3; i++){
scanf("%s %s %d", book1[i].name, book1[i].title, &book1[i].page);
}

for(i=0; i<3; i++){
printf("%s %s %d \n", book1[i].name, book1[i].title, book1[i].page);
}

free(book1); // 동적할당 해제
return 0;
}

// 동적할당은 마치 포인터처럼 접근한다.
// struct book book1[3];
// struct book *pt = &book1[0]; (또는 book1)
// 포인터는 pt[i].name 또는 (pt+i)->name로 접근하는 형태를 보인다.

2. 반복문 실행할 때마다 동적할당
#include <stdio.h>
#include <stdlib.h>
struct book{
char name[20];
char title[20];
int page;
};

int main(){
int i;
struct book *book2[3];

for(i=0; i<3; i++){
struct book *book1 = (struct book*)malloc(sizeof(struct book)*1); // 동적할당
scanf("%s %s %d", book1->name, book1->title, &(book1->page));
book2[i] = book1;
}

for(i=0; i<3; i++){
printf("%s %s %d \n", book2[i]->name, book2[i]->title, book2[i]->page);
free(book2[i]); // 동적할당 해제
}
return 0;
}

// 포인터배열을 만들어줬고 반복문 실행시 동적할당했다.
// book2에는 3개의 동적할당이 담겨있다.

블로그 이미지

ryancha9

https://blog.naver.com/7246lsy

,