본문 바로가기
c

9. 메모리 동적 할당

by it_jangyee 2020. 3. 19.

1. 메모리

1) 스택: 함수가 사용하는 메모리. 함수의 지역변수, 파라메터 할당.
정적메모리: static 변수나 전역변수 저장
스택/정적메모리: 변수를 선언해서 메모리를 할당받음. 

2) 힙 : 메모리 동적할당(런타임시에 할당받음). 변수선언으로는 할당받지 못함.
malloc() 함수로 할당 받는다

 malloc(할당받을 메모리 크기): 할당받은 메모리 주소 반환
void *p = malloc(4);

3) void 포인터

void 포인터는 타입이 지정되지 않은 포인터로 어느 주소나 저장가능. 연산하기 전 캐스팅 필수

#include <stdio.h>
void main(){
    char a='x', *p1=&a;
    int b=10, *p2 = &b;
    float c = 3.45f, *p3=&c;
    void *vp;

    printf("a=%c, *p1=%c\n", a, *p1);
    printf("b=%d, *p2=%d\n", b, *p2);
    printf("c=%f, *p3=%f\n", c, *p3);

    vp = &a;
    printf("a=%c, *vp=%c\n", a, *(char*)vp);

    vp = &b;
    printf("b=%d, *vp=%d\n", b, *(int*)vp);

    vp = &c;
    printf("c=%f, *vp=%f\n", c, *(float*)vp);
}

4) malloc()으로 동적할당

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

void main(){

    int *p;

    p = (int*)malloc(sizeof(int));
    *p = 10;

    printf("*p=%d\n", *p);

    free(p); //메모리 해제
}

free(): 동적 할당한 메모리 해제

 

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

void main(){
    char *p1;
    int *p2;
    float *p3;

    p1 = (char*)malloc(sizeof(char));
    *p1 = 'q';

    p2 = (int*)malloc(sizeof(int));
    *p2 = 123;

    p3 = (float*)malloc(sizeof(float));
    *p3 = 5.678f;

    printf("*p1=%c, *p2=%d, *p3=%f\n", *p1, *p2, *p3);

    free(p1);
    free(p2);
    free(p3);
}
#include <stdio.h>
#include <stdlib.h>

void main(){
    char *p1;
    int *p2;
    int i;

    p1 = (char*)malloc(sizeof(char)*6);
    p1="hello";

    p2 = (int*)malloc(sizeof(int)*3);
    for(i=0;i<3;i++){
        p2[i]=i+1;
    }

    printf("p1 = %s\n", p1);
    for(i=0;i<3;i++){
        printf("p2[%d]=%d\n", i, p2[i]);
    }

    free(p1);
    free(p2);
}
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

struct Student{
    int num;
    char name[10];
    int score;
};

void main(){
    struct Student *s1;
    s1 = (struct Student*)malloc(sizeof(struct Student));
    s1->num=1;
    strcpy(s1->name,"가나다");
    s1->score=78;

    printf("s1->num:%d, s1->name:%s, s1->score:%d\n",
           s1->num, s1->name, s1->score);

    free(s1);
}
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

struct Student{
    int num;
    char name[10];
    int score;
};

void main(){
    struct Student *s1;
    int i;
    s1 = (struct Student*)malloc(sizeof(struct Student)*3);

    for(i=0;i<3;i++){
        printf("%d번째 학생정보 입력\n", i+1);
        printf("num:");
        scanf("%d", &s1[i].num);
        printf("name:");
        scanf("%s", s1[i].name);
        printf("score:");
        scanf("%d", &s1[i].score);
    }
    printf("num\tname\tscore\n");
    for(i=0;i<3;i++){
        printf("%d\t%s\t%d\n",
               s1[i].num, s1[i].name, s1[i].score);
    }

    free(s1);
}

5) 1중 링크드 리스트

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

struct Node{
    int num;
    struct Node *next;
};
void main(){
    struct Node *head=NULL, *tail, *bmp;
    int flag = 1;
    while(flag){
        bmp = (struct Node*)malloc(sizeof(struct Node));
        printf("숫자를 입력하라\n");
        scanf("%d", &bmp->num);
        if(head==NULL){
            head=bmp;
        }else{
            tail->next=bmp;
        }
        tail=bmp;
        tail->next=NULL;

        printf("계속하겠나? 멈추려면 0을 입력하라\n");
        scanf("%d", &flag);
    }

    bmp = head;//bmp를 첫 번째 노드로 이동
    while(bmp!=NULL){
        printf("%d\n", bmp->num);//bmp가 가르키는 노드의 num출력
        bmp = bmp->next;
    }

    while(head!=NULL){
        bmp=head;
        head=head->next;
        printf("%d노드 삭제\n", bmp->num);
        free(bmp);
    }
}

6) 2중 링크드 리스트

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

struct Node{
    int num;
    struct Node *next;//다음 노드 주소
    struct Node *prev;//앞 노드 주소
};
void main(){
    struct Node *head=NULL, *tail, *bmp;
    int flag = 1;
    while(flag){
        bmp = (struct Node*)malloc(sizeof(struct Node));
        printf("숫자를 입력하라\n");
        scanf("%d", &bmp->num);
        if(head==NULL){
            head=bmp;
            head->prev=NULL;
        }else{
            tail->next=bmp;
            bmp->prev=tail;
        }
        tail=bmp;
        tail->next=NULL;

        printf("계속하겠나? 멈추려면 0을 입력하라\n");
        scanf("%d", &flag);
    }

    puts("head부터 순서대로 출력");
    bmp = head;//bmp를 첫 번째 노드로 이동
    while(bmp!=NULL){
        printf("%d\n", bmp->num);//bmp가 가르키는 노드의 num출력
        bmp = bmp->next;
    }

    puts("tail부터 역순으로 출력");
    bmp = tail;
    while(bmp!=NULL){
        printf("%d\n", bmp->num);
        bmp = bmp->prev;
    }
   
   //노드 역순으로 삭제
    while(tail!=NULL){
        bmp=tail;
        tail=tail->prev;
        if(tail!=NULL){
            tail->next=NULL;
        }
        printf("%d노드 삭제\n", bmp->num);
        free(bmp);
    }

/*
    while(head!=NULL){
        bmp=head;
        head=head->next;
        printf("%d노드 삭제\n", bmp->num);
        free(bmp);
    }
*/
}

'c' 카테고리의 다른 글

8. 구조체  (0) 2020.02.24
7. 입출력  (0) 2020.02.19
6. 포인터  (0) 2020.02.17
5. 함수  (0) 2020.02.12
4. 배열  (0) 2020.01.22

댓글