Upload
others
View
1
Download
0
Embed Size (px)
Citation preview
제14장 동적 메모리 할당
Dynamic Allocation◦ void * malloc(sizeof(char)*256)◦ void * calloc(sizeof(char), 256)◦ void * realloc(void *, size_t);
Self-Referece NODEstruct selfref {
int n;struct selfref *next;
};
Linked Liststruct linked_list {
char *name;struct linked_list *next;
};typedef struct linked_list NODE;typedef NODE * LINK ; 한밭대 정보통신공학과 и чунг хо 2
스택영역(형식매개변수, 지역변수): 작은 주소값 데이터영역(전역변수, 정적변수): 중간 주소값 Heap 영역(동적할당변수): 큰 주소값 영역 동적메모리 할당은 Heap영역에 대량의 메모리를확보
#include <stdlib.h> //포함시켜야할 헤더 void *malloc(sizeof(data type)*개수); void *calloc(개수,sizeof(data type)); void *realloc(void *, size_t);
한밭대 정보통신공학과 и чунг хо 3
void *malloc(sizeof(data type)*개수);int a[5]={0,1,2,3,4};위와 같은 것을 malloc()으로 같은 효과를 주려면int *pi, i;pi = (int *) malloc(sizeof(int)*5);for(i=0;i<5;i++)
pi[i]=i;free(pi);
한밭대 정보통신공학과 и чунг хо 4
한밭대 정보통신공학과 и чунг хо
//1에서 6까지의 주사위 값으로 생성하는 프로그램#include <stdio.h> #include <stdlib.h>#include <time.h>int main(){int *p, n, i;printf("Input n: "); scanf("%d", &n);p=(int *)malloc(sizeof(int)*n);//입력 n크기 만큼 동적 배열 생성srand(time(NULL)); //실행 시마다 다른 결과가 나타나도록 함.for(i=0;i<n;i++)printf("%1d ", rand()%6+1); //랜덤한 주사위 값이 나오도록 함.return 0;
}
5
한밭대 정보통신공학과 и чунг хо
#include <stdio.h>#include <stdlib.h>#include <time.h>int main(){int **p, rows, cols, i,j;printf("Input rows cols: "); scanf("%d%d", &rows, &cols);p=(int **)malloc(sizeof(int *)*(rows+1)); //각 행의 포인터 수만큼 확보for(i=0;i<rows;i++)
p[i]=(int *)malloc(sizeof(int)*cols);//각 행의 원소의 수만큼p[i]=NULL; //row+1의 1에 해당하는 부분의 마지막을 NULL로 채움.srand(time(NULL)); //실행 시 마다 다른 결과를 내도록 함.for(i=0;i<rows;i++)
for(j=0;j<cols;j++)p[i][j]= rand()%10; //0에서 9까지의 랜덤한 수로 채움.
for(i=0;i<rows;i++){ //프린트하는 부분for(j=0;j<cols;j++)
printf("%2d ", p[i][j]);printf("\n");
}6
void *calloc(개수,sizeof(data type)); calloc()은 0으로 초기화시키고, malloc()보다 속도가 빠르다.int a[5]={0,1,2,3,4};위와 같은 것을 calloc()으로 같은 효과를 주려면int *pi, i;pi = (int *) calloc(5, sizeof(int));for(i=0;i<5;i++)
pi[i]=i;free(pi);
한밭대 정보통신공학과 и чунг хо 7
void *realloc(void *, size_t); //초기화 0으로 안 됨int *pi, *repi, i;pi = (int *) calloc(5, sizeof(int));for(i=0;i<5;i++)
pi[i]=i; //0 1 2 3 4repi = (int *)realloc(pi, 7*sizeof(int));for(i=5;i<7;i++)
pi[i]=i; //5 6free(pi);
한밭대 정보통신공학과 и чунг хо 8
데이터와 포인터를 포함하는 구조체 포인터가 다름 구조체를 가리키도록 함 형태
struct selfref {int data;struct selfref *next;
};typedef struct selfref list;
한밭대 정보통신공학과 и чунг хо 9
데이터와 포인터를 포함하는 구조체first = (list *)malloc(sizeof(list));second = (list *)malloc(sizeof(list));first->data = 100;second->data = 200;second->next = NULLfirst->next = second;
한밭대 정보통신공학과 и чунг хо 10
자기참조구조체 이용 헤드: 연결리스트의 첫번째 원소, 마지막 원소는 NULL 형태struct LikedList {
char *str;struct list *next;
};typedef struct LinkedList NODE;typedef NODE *LINK;
한밭대 정보통신공학과 и чунг хо 11
LINK cur;char str[] = “C++”; //복사해 넣을 내용cur = (NODE *)malloc(sizeof(NODE));cur->str =(char*)malloc(sizeof(char)*(strlen(str)+1));strcpy(cur->data, str); //문자열을 데이터에 복사
cur->next = NULL; //append할 것이므로 항상 맨마지막이 됨. 다른 노드를 연결하려면 다른 구조체를가리키도록 대입하면 됨.
한밭대 정보통신공학과 и чунг хо 12
자기참조구조체를 한 개 만들고 이를 cur라 한다. Append()라는 함수를 이용하여 데이터가 없으면 맨 앞에 추가한다.
이미 다른 데이터가 있으면 연결리스트의 끝을 찾아서맨 뒤에 추가한다.
마지막 노드를 찾아가는 방법LINK nextNode = head;if(head==NULL) //연결리스트에 노드가 없으면 추가{
head = cur;return head;
}
한밭대 정보통신공학과 и чунг хо 13
연결리스트에 노드가 있으면while (nextNode->next !=NULL) // {
nextNode = nextNode->next;} nextNode->next = cur;
한밭대 정보통신공학과 и чунг хо 14
#include <stdio.h>int main(){printf("경로: %s\n", __FILE__);printf("컴파일시각:%s\n", __TIME__);printf("컴파일년월일:%s\n", __DATE__);printf("줄번호: %d\n", __LINE__);return 0;}
한밭대 정보통신공학과 и чунг хо 15
운영체제 등의 환경이 다를 때 손 쉽게 이를 맞춰 주려고할 때 사용#if SYSTEM == WINDOWS#include “stdio.h”#elif SYSTEM == MAC //else if 의 의미#incude “vax.h”#elif SYSTEM == UNIX#include “unix.h”#else#include “etc.h”#endif
한밭대 정보통신공학과 и чунг хо 16
#define DEBUG#ifdef DEBUG
………………//여기에 있는 부분을 실행한다.#endif//#define DEBUG가 정의되어 있지 않으면//#ifdef DEBUG 에서 #endif 사이가 컴파일되지 않//는다.#ifndef //if not define의 의미 #ifdef과 반대의미예) #ifndef LIMIT
#define LIMIT 256#endif
한밭대 정보통신공학과 и чунг хо 17
#define 의 해지#define LIMIT 256#undef LIMIT
복잡한 전처리기 지시자는 잘 쓰이지 않으므로 필요시 책을 참고하기 바람.
한밭대 정보통신공학과 и чунг хо 18
한밭대 정보통신공학과 и чунг хо
구조체 Structure◦ Struct TAGNAME { int a; double b; char c[12];} s;◦ Allocation of Initial Value◦ Structure Array◦ Reference of Structure Members
공용체 Union◦ Union TAGNAME { int a; double b; char c[12];}◦ Data usage, length of union
열거형 Enum◦ enum color {yellow, red, blue, magenta, green}
col;
Dynamic Allocation◦ void * malloc(sizeof(char)*256)◦ void * calloc(sizeof(char), 256)◦ void * realloc(void *, size_t);
Self-Referece NODEstruct selfref {
int n;struct selfref *next;
};
Linked Liststruct linked_list {
char *name;struct linked_list *next;
};typedef struct linked_list NODE;typedef NODE * LINK ; 19