topic난이도 · 약 20

구조체

서로 다른 타입의 변수를 하나로 묶는 사용자 정의 타입. 멤버 접근은 `.`, 포인터는 `->`.

#C#구조체
왜 배우는가

`.`과 `->` 혼동이 실기 단골. 구조체 포인터는 Java 객체 참조와 유사한 역할.

c
struct Point {
    int x;
    int y;
};

int main() {
    struct Point p1 = {10, 20};
    struct Point *pp = &p1;

    printf("%d\n", p1.x);      // 10  (직접 접근)
    printf("%d\n", (*pp).x);   // 10  (역참조 후 .)
    printf("%d\n", pp->x);     // 10  (화살표 단축)
    return 0;
}

법칙 — 구조체 변수는 `.`, 구조체 포인터는 `->`. `pp->x`는 `(*pp).x`의 단축 표기.

c
// 구조체 배열
struct Student {
    char name[20];
    int score;
};

struct Student arr[3] = {
    {"홍길동", 85},
    {"이순신", 90},
    {"세종", 95}
};

int total = 0;
for (int i = 0; i < 3; i++)
    total += arr[i].score;
printf("%d", total);  // 270

typedef — `typedef struct Point { int x, y; } Point;` 이후로는 `struct`를 빼고 `Point p1;`처럼 쓸 수 있다. 가독성을 위한 일반적 관행.

실기 드릴 1문항
code실기 드릴 · 코드 추적

다음 C 코드의 출력은?

c
#include <stdio.h>
struct Box {
    int w;
    int h;
};
int main() {
    struct Box b = {3, 4};
    struct Box *p = &b;
    p->w += 2;
    (*p).h *= 2;
    printf("%d,%d", b.w, b.h);
    return 0;
}