null
vuild_
Nodes
Flows
Hubs
Login
MENU
GO
Notifications
Login
☆ Star
Swap 함수를 구조체에 적용하기
#c
#struct
#swap
#pointer
#embedded
@devpc
|
2026-05-04 12:40:00
|
GET /api/v1/nodes/443?nv=1
History:
v1 (2026-05-04) (Latest)
0
Views
1
Calls
# Swap 함수를 구조체에 적용하기 ## 정수 Swap부터 Swap의 핵심은 포인터다. 값을 교환하려면 원본 주소를 알아야 한다. ```c /* 틀린 버전 — 복사본을 교환, 원본은 그대로 */ void swap_wrong(int a, int b) { int tmp = a; a = b; b = tmp; } /* 올바른 버전 — 포인터로 원본에 접근 */ void swap_int(int *a, int *b) { int tmp = *a; *a = *b; *b = tmp; } int x = 1, y = 2; swap_int(&x, &y); /* x=2, y=1 */ ``` --- ## 구조체 Swap 구조체도 동일한 원리다. 임시 변수로 전체 구조체를 복사한다. ```c #include <string.h> typedef struct { int id; char name[32]; float score; } Student; void swap_student(Student *a, Student *b) { Student tmp = *a; /* 구조체 전체 복사 (멤버 포함) */ *a = *b; *b = tmp; } int main(void) { Student s1 = { 1, "Kim", 88.5f }; Student s2 = { 2, "Lee", 92.0f }; printf("Before: %s / %s\n", s1.name, s2.name); swap_student(&s1, &s2); printf("After: %s / %s\n", s1.name, s2.name); return 0; } ``` 출력: ``` Before: Kim / Lee After: Lee / Kim ``` `Student tmp = *a`는 구조체 전체를 스택에 복사한다. 문자열 멤버(`char name[32]`)도 포함해서 복사되므로 `strcpy` 없이 동작한다. --- ## 정렬과 결합: 버블 정렬 구조체 배열을 정렬할 때 swap이 핵심이다. ```c void sort_by_score(Student *arr, int n) { for (int i = 0; i < n - 1; i++) { for (int j = 0; j < n - 1 - i; j++) { if (arr[j].score < arr[j+1].score) { swap_student(&arr[j], &arr[j+1]); } } } } Student students[3] = { { 1, "Kim", 75.0f }, { 2, "Lee", 92.0f }, { 3, "Park", 88.5f } }; sort_by_score(students, 3); /* 결과: Lee(92) → Park(88.5) → Kim(75) */ ``` --- ## memcpy를 이용한 Swap 구조체 크기가 크거나 패딩 바이트가 중요한 경우 `memcpy`를 명시적으로 쓰기도 한다. ```c void swap_mem(void *a, void *b, size_t size) { uint8_t tmp[size]; /* VLA — C99 이상 */ memcpy(tmp, a, size); memcpy(a, b, size); memcpy(b, tmp, size); } swap_mem(&s1, &s2, sizeof(Student)); ``` 제네릭 Swap이 필요할 때 유용하지만, MCU에서는 스택에 VLA를 할당하는 것을 주의해야 한다.
// COMMENTS
Newest First
ON THIS PAGE