Learning
레슨 3 / 8·20분

구조체와 메모리

구조체 (struct)

struct는 서로 다른 타입의 데이터를 하나로 묶는 사용자 정의 타입입니다. 관련된 데이터를 논리적으로 그룹화할 때 사용합니다.

c
#include <stdio.h>
#include <string.h>

// 구조체 정의
struct Student {
    char name[50];
    int age;
    float gpa;
};

void printStudent(struct Student s) {
    printf("이름: %s, 나이: %d, 학점: %.1f\n",
           s.name, s.age, s.gpa);
}

int main() {
    // 구조체 변수 생성
    struct Student s1;
    strcpy(s1.name, "김철수");
    s1.age = 20;
    s1.gpa = 3.8f;

    // 초기화 리스트 사용
    struct Student s2 = {"이영희", 22, 4.0f};

    printStudent(s1);  // 이름: 김철수, 나이: 20, 학점: 3.8
    printStudent(s2);  // 이름: 이영희, 나이: 22, 학점: 4.0

    return 0;
}

동적 메모리 관리

malloc으로 힙(heap) 메모리를 할당하고, free로 해제합니다. sizeof 연산자는 타입의 크기(바이트)를 반환합니다. 동적 할당은 크기가 실행 중에 결정되는 데이터에 필수적입니다.

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

int main() {
    // 동적 배열 할당
    int n = 5;
    int *arr = (int *)malloc(n * sizeof(int));

    if (arr == NULL) {
        printf("메모리 할당 실패!\n");
        return 1;
    }

    // 값 채우기
    for (int i = 0; i < n; i++) {
        arr[i] = (i + 1) * 10;
    }

    // 출력
    for (int i = 0; i < n; i++) {
        printf("%d ", arr[i]);  // 10 20 30 40 50
    }
    printf("\n");

    // 반드시 해제!
    free(arr);
    arr = NULL;  // dangling pointer 방지

    // 구조체 동적 할당
    struct Student *sp = (struct Student *)malloc(sizeof(struct Student));
    if (sp != NULL) {
        strcpy(sp->name, "박민수");  // -> 연산자: 포인터로 멤버 접근
        sp->age = 21;
        sp->gpa = 3.5f;

        printf("%s (나이: %d)\n", sp->name, sp->age);
        free(sp);
    }

    return 0;
}
  • malloc(size) — size 바이트 만큼 힙 메모리 할당
  • free(ptr) — 할당된 메모리 해제
  • sizeof(type) — 타입의 크기(바이트) 반환
  • -> — 포인터로 구조체 멤버에 접근
  • calloc(n, size) — 0으로 초기화된 메모리 할당
  • realloc(ptr, new_size) — 메모리 크기 변경
💡

malloc 후 반드시 free를 호출하세요. 그렇지 않으면 메모리 누수(memory leak)가 발생합니다. 해제 후에는 포인터를 NULL로 설정하는 것이 안전합니다.