null
vuild_
Nodes
Flows
Hubs
Login
MENU
Notifications
Login
☆ Star
구조체 기초 (Struct Basics)
#c
#c-lang
#intermediate
#struct
#typedef
@devpc
|
2026-03-29 12:57:39
|
GET /api/v1/nodes/49?nv=2
History:
v2 (2026-03-29) (Latest)
v1 (2026-03-29)
0
Views
5
Calls
# 구조체 기초 (Struct Basics) ## 구조체란? 서로 다른 타입의 변수를 **하나의 묶음**으로 정의하는 사용자 정의 타입입니다. ```c struct Point { int x; int y; }; ``` --- ## 구조체 선언과 초기화 ```c struct Student { char name[50]; int age; float gpa; }; // 방법 1 — 지정 초기화 (C99 이상) struct Student s1 = { .name = "Alice", .age = 20, .gpa = 3.8f }; // 방법 2 — 순서 초기화 struct Student s2 = { "Bob", 22, 3.5f }; // 방법 3 — 선언 후 개별 대입 struct Student s3; strcpy(s3.name, "Charlie"); s3.age = 21; s3.gpa = 3.2f; ``` --- ## 멤버 접근 — `.` 연산자 구조체 변수에서 멤버에 접근할 때 사용합니다. ```c struct Point p = { .x = 3, .y = 4 }; printf("x = %d\n", p.x); // 3 printf("y = %d\n", p.y); // 4 p.x = 10; // 멤버 값 변경 ``` --- ## 멤버 접근 — `->` 연산자 (포인터) 구조체 **포인터**를 통해 멤버에 접근할 때 사용합니다. ```c struct Point p = { 3, 4 }; struct Point *pp = &p; // (*pp).x 와 pp->x 는 동일 printf("x = %d\n", pp->x); // 3 pp->y = 100; printf("y = %d\n", p.y); // 100 ``` | 상황 | 연산자 | 예시 | |------|--------|------| | 구조체 변수 | `.` | `s.age` | | 구조체 포인터 | `->` | `sp->age` | --- ## typedef — 타입 별칭 매번 `struct` 키워드를 쓰지 않도록 별칭을 정의합니다. ```c // typedef 없이 struct Point p1; // typedef 사용 typedef struct Point { int x; int y; } Point; Point p2; // struct 없이 사용 가능 Point p3 = { 1, 2 }; ``` ### 익명 구조체 + typedef ```c typedef struct { char name[50]; int age; } Person; Person p = { "Alice", 30 }; printf("%s is %d years old\n", p.name, p.age); ``` --- ## 구조체 크기 — sizeof와 패딩 구조체의 크기는 멤버 크기의 합이 아닐 수 있습니다. 컴파일러가 **정렬(alignment)** 을 위해 패딩을 삽입합니다. ```c typedef struct { char a; // 1바이트 + 3바이트 패딩 int b; // 4바이트 char c; // 1바이트 + 3바이트 패딩 } Example; printf("%zu\n", sizeof(Example)); // 12 (1+3+4+1+3) ``` ``` 메모리 레이아웃: [a][pad][pad][pad][b b b b][c][pad][pad][pad] 1 1 1 1 4 1 1 1 1 = 12바이트 ``` > 멤버 순서를 **큰 타입 → 작은 타입** 순으로 배치하면 패딩을 줄일 수 있습니다. --- ## 구조체를 함수에 전달 ```c // 값 전달 — 구조체 전체 복사 (큰 구조체엔 비효율적) void print_point(struct Point p) { printf("(%d, %d)\n", p.x, p.y); } // 포인터 전달 — 복사 없이 원본 접근 (권장) void move_point(struct Point *p, int dx, int dy) { p->x += dx; p->y += dy; } ``` --- ## 전체 예제 ```c #include <stdio.h> #include <string.h> typedef struct { char name[50]; int age; float gpa; } Student; void print_student(const Student *s) { printf("이름: %s, 나이: %d, GPA: %.1f\n", s->name, s->age, s->gpa); } int main(void) { Student s1 = { "Alice", 20, 3.8f }; Student s2; strcpy(s2.name, "Bob"); s2.age = 22; s2.gpa = 3.5f; print_student(&s1); print_student(&s2); return 0; } ``` --- ## 정리 | 개념 | 내용 | |------|------| | `struct` | 사용자 정의 복합 타입 | | `.` 연산자 | 구조체 변수의 멤버 접근 | | `->` 연산자 | 구조체 포인터의 멤버 접근 | | `typedef` | 구조체에 별칭 부여 | | 패딩 | 정렬을 위해 컴파일러가 삽입하는 여분 바이트 | ---
// COMMENTS
ON THIS PAGE