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개의 동적할당이 담겨있다.
'C' 카테고리의 다른 글
[C] 중첩 구조체 / 구조체 변수가 포인터일 때 (0) | 2019.12.04 |
---|---|
[C] 2차원 배열의 표현 (0) | 2019.12.04 |
[C] 변수형 문자열 상수형 문자열 (0) | 2019.12.03 |
[C] 조건부 컴파일 #if #else #elif #endif #ifdef #ifndef (0) | 2019.12.03 |
[C] 파일 위치지시자 fseek (0) | 2019.12.03 |