52.4 연습문제: 2차원 좌표 초기화하기

다음 소스 코드를 완성하여 0 0 0 0이 출력되게 만드세요.

practice_struct_memory_set.c

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

①_______________________

struct Point2D {
    int x;
    int y;
};

int main()
{
    struct Point2D p;
    struct Point2D *ptr = malloc(sizeof(struct Point2D));

    memset(②____________________________);
    memset(③____________________________);

    printf("%d %d %d %d\n", p.x, p.y, ptr->x, ptr->y);

    free(ptr);

    return 0;
}

실행 결과

0 0 0 0

정답

① #include <string.h> 또는 #include <memory.h>
② &p, 0, sizeof(struct Point2D)
③ ptr, 0, sizeof(struct Point2D)

해설

먼저 memset 함수를 사용하려면 string.h 또는 memory.h 헤더 파일을 포함해야 합니다.

memset 함수를 사용하여 구조체 변수와 구조체 포인터의 메모리를 0으로 설정해야 합니다. 따라서 구조체 변수 p는 앞에 &를 사용하여 메모리 주소를 구해서 넣어주고, 구조체 포인터 ptr은 포인터이므로 그대로 넣어줍니다. 그리고 설정할 값 0과 구조체 크기를 구해서 넣어주면 됩니다.