malloc()함수
malloc()함수는 heap영역에 메모리를 할당한다. 메모리의 부족으로 할당에 실패하면 NULL을 반환.
프로그램의 실행이 끝나기 전에 반드시 free()함수를 호출하여 할당을 해제해 주어야한다. 만약 해제하지 않으면
메모리에 그대로 남아있어 계속 쌓이다 보면 결국 메모리의 용량이 부족하게 되는 현상이 나타난다.
프로그램의 실행이 끝나기 전에 반드시 free()함수를 호출하여 할당을 해제해 주어야한다. 만약 해제하지 않으면
메모리에 그대로 남아있어 계속 쌓이다 보면 결국 메모리의 용량이 부족하게 되는 현상이 나타난다.
#include <stdio.h>
#include <stdlib.h> // malloc() 함수 사용
#include <string.h> // strcpy() 함수 사용
typedef struct tag_student
{
char name[20];
int score;
} student;
int main()
{
student st[3];
student *sp;
int i;
sp=(student*)malloc(sizeof(student));
if(sp==NULL)
{ // 메모리 할당 실패할 경우
printf("allocation error\n");
exit(-1); // 프로그램을 종료 (return(main함수를 종료)을 추천)
}
i=0; // 초기화는 반복문 앞에 써주는 것이 좋다.
while(i<3)
{
printf("Please enter student name & score : ");
scanf("%s %d", sp->name, &sp->score);
//strcpy(st[i].name, sp->name); // 배열에 복사
//st[i++].score=sp->score;
st[i++]=*sp; // 위와 같다.
}
free(sp);
for(i=0; i<3; i++)
{
printf("student name : %s,\tscore : %d\n", st[i].name, st[i].score);
}
return 0;
}
#include <stdlib.h> // malloc() 함수 사용
#include <string.h> // strcpy() 함수 사용
typedef struct tag_student
{
char name[20];
int score;
} student;
int main()
{
student st[3];
student *sp;
int i;
sp=(student*)malloc(sizeof(student));
if(sp==NULL)
{ // 메모리 할당 실패할 경우
printf("allocation error\n");
exit(-1); // 프로그램을 종료 (return(main함수를 종료)을 추천)
}
i=0; // 초기화는 반복문 앞에 써주는 것이 좋다.
while(i<3)
{
printf("Please enter student name & score : ");
scanf("%s %d", sp->name, &sp->score);
//strcpy(st[i].name, sp->name); // 배열에 복사
//st[i++].score=sp->score;
st[i++]=*sp; // 위와 같다.
}
free(sp);
for(i=0; i<3; i++)
{
printf("student name : %s,\tscore : %d\n", st[i].name, st[i].score);
}
return 0;
}
'C언어 > 강의' 카테고리의 다른 글
2010년 12월 13일 월요일 (저장 클래스) (0) | 2010.12.13 |
---|---|
2010년 12월 13일 월요일 (리다이렉션) (0) | 2010.12.13 |
2010년 11월 30일 화요일 구조체의 정적 연결리스트 (static linked list) (0) | 2010.11.30 |
2010년 11월 29일 월요일 구조체 사용자정의 (struct) & 구조체 초기화 (0) | 2010.11.29 |
2010년 11월 19일 금요일 (0) | 2010.11.19 |