8.05.2017

0805 자료구조 복습

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

void main() {
        /*
        정적할당 : 고정되어있는 값만 사용
                     ex) int num, int arr[5];
        동적할당 : 계속해서 변하는 값
                           컴파일을 실행할 때 저장할 변수를 늘리거나 줄일 때 사용
                           #include <stdlib.h>
        할당 : malloc(), calloc()  //재할당 : realloc()
        */

        //(void*)malloc(바이트크기)
        int* p = (int*)malloc(sizeof(int) * 4);
        // malloc를 이용하여 4개짜리 배열
        // 생성 후, 포인터 변수 p 에 배열의 첫번쨰 인덱스의 주소(배열의 시작주소)를 대입해줬다.

        /*
        0번째 인덱스 = 10, 1 = 20, 2 = 30
        */


        /*int arr[5];
        int* p;
        */

        *p = 10;
        p[1] = 20;
        p[2] = 30;

        printf("%d %d %d \n", *(p + 0), p[1], p[2]);

        //calloc(개수, 사이즈);
        // c : clean
        // 값이 없을 경우엔 0으로 초기화
        int* c = (int*)calloc(4, sizeof(int));
        *&c[0] = 50;
        c[1] = 60;
        c[2] = 70;
        printf("%d %d %d \n", c[0], c[1], c[2]);
        printf("c : %d, m : %d \n", c[3], p[3]);

        //_msize() : 동적할당된 배열의 사이즈
        // sizeof : 정적할당된 변수

        printf("&dbyte \n", _msize(p)); //16byte
        printf("&dbyte \n", _msize(c)); //16byte

        //realloc(누구, 사이즈?);
        p = (int*)realloc(p, sizeof(int)* 5);
        //4개짜리 공간 -> 5개짜리 공간
        printf("%dbyte \n", _msize(p)); //20byte
        printf("%d %d %d \n", p[0], p[1], p[2]); //20byte


        /*
        *& : 서로 상쇄
        &* 상쇄(X)
        arr[0] == *p == *(p+0) == *&p[0] == p[0]
        arr[1] == *(p+1) == *&p[1] == p[1]
        */
        /*int num;
        int *p2 = &num;
        *p2 = 20;
        */

        // *p2 == num
        // p2가 가지고 있는 주소로 접근(num으로 이동)하여 20을 대입하겠다.
}

댓글 없음:

댓글 쓰기