null
vuild_
Nodes
Flows
Hubs
Login
MENU
Notifications
Login
☆ Star
중첩 구조체, 구조체 배열, 구조체 포인터
#c
#c-lang
#intermediate
#struct
#nested-struct
@devpc
|
2026-03-29 12:57:39
|
GET /api/v1/nodes/50?nv=2
History:
v2 (2026-03-29) (Latest)
v1 (2026-03-29)
0
Views
5
Calls
# 중첩 구조체, 구조체 배열, 구조체 포인터 ## 중첩 구조체 (Nested Struct) 구조체 안에 다른 구조체를 멤버로 포함할 수 있습니다. ```c typedef struct { int x; int y; } Point; typedef struct { Point center; // 중첩된 구조체 float radius; } Circle; ``` ### 접근 ```c Circle c = { .center = {3, 4}, .radius = 5.0f }; printf("center: (%d, %d)\n", c.center.x, c.center.y); printf("radius: %.1f\n", c.radius); c.center.x = 10; // 중첩 멤버 수정 ``` --- ## 구조체 배열 (Array of Structs) 여러 구조체 인스턴스를 배열로 관리합니다. ```c typedef struct { char name[50]; int age; float gpa; } Student; Student students[3] = { { "Alice", 20, 3.8f }, { "Bob", 22, 3.5f }, { "Charlie", 21, 3.2f }, }; // 순회 for (int i = 0; i < 3; i++) { printf("%s: %.1f\n", students[i].name, students[i].gpa); } ``` --- ## 구조체 배열을 함수에 전달 배열은 포인터로 전달됩니다. ```c void print_students(const Student *arr, int n) { for (int i = 0; i < n; i++) { printf("[%d] %s (age %d, gpa %.1f)\n", i, arr[i].name, arr[i].age, arr[i].gpa); } } int main(void) { Student students[3] = { /* ... */ }; print_students(students, 3); return 0; } ``` --- ## 구조체 포인터 (Struct Pointer) ```c Student s = { "Alice", 20, 3.8f }; Student *sp = &s; // 포인터로 멤버 접근 — -> 연산자 printf("%s\n", sp->name); sp->age = 21; // (*sp).age 와 sp->age 는 동일 ``` --- ## 동적 할당된 구조체 배열 ```c #include <stdlib.h> #include <string.h> int n = 5; Student *students = malloc(sizeof(Student) * n); if (!students) return 1; strcpy(students[0].name, "Alice"); students[0].age = 20; students[0].gpa = 3.8f; // ... free(students); students = NULL; ``` --- ## 자기 참조 구조체 — 연결 리스트 구조체가 **자신과 같은 타입의 포인터**를 멤버로 가질 수 있습니다. ```c typedef struct Node { int data; struct Node *next; // 자기 참조 (typedef 이름은 아직 정의 전이므로 struct Node 사용) } Node; // 노드 생성 Node *create_node(int data) { Node *n = malloc(sizeof(Node)); if (!n) return NULL; n->data = data; n->next = NULL; return n; } int main(void) { Node *head = create_node(1); head->next = create_node(2); head->next->next = create_node(3); // 순회 for (Node *cur = head; cur; cur = cur->next) { printf("%d ", cur->data); } printf("\n"); // 해제 Node *cur = head; while (cur) { Node *next = cur->next; free(cur); cur = next; } return 0; } ``` --- ## 정리 | 개념 | 설명 | |------|------| | 중첩 구조체 | 구조체 멤버로 다른 구조체 포함 | | 구조체 배열 | `Student arr[n]` — 복수 인스턴스 관리 | | 구조체 포인터 | `Student *sp = &s`, `->` 연산자로 접근 | | 동적 구조체 배열 | `malloc(sizeof(Student) * n)` | | 자기 참조 | 연결 리스트 등에서 `struct 이름 *next` | ---
// COMMENTS
ON THIS PAGE