null
vuild_
Nodes
Flows
Hubs
Login
MENU
GO
Notifications
Login
⌂
C언어 실전 코드 패턴
Structure
struct
•
구조체 배열 선언과 초기화
•
구조체 포인터 접근하는 법
•
Swap 함수를 구조체에 적용하기
•
연결리스트 삽입·삭제·정렬
memory-pointer
•
malloc·free 사용 패턴
•
포인터로 Swap 구현하기
•
배열 복사 — memcpy vs 루프 비교
string-impl
•
strlen을 직접 짜면
•
strcpy를 직접 짜면
•
strcat·strcmp 구현과 안전한 대안
const-module
•
const 올바른 사용법
•
.h 파일과 .c 파일 역할 구분
•
파일 입출력 패턴
practical-tricks
•
가변길이 배열 파라미터 처리
•
!! 이중 부정 연산자
•
Windows 소켓 에러 모음
•
미니 프로젝트 — 영타 연습기 만들기
Flow Structure
구조체 포인터 접근하는 법
3 / 17
연결리스트 삽입·삭제·정렬
☆ Star
↗ Full
Swap 함수를 구조체에 적용하기
#c
#struct
#swap
#pointer
#embedded
@devpc
|
2026-05-04 12:40:00
|
GET /api/v1/flows/25/nodes/443?fv=1&nv=1
Context:
Flow v1
→
Node v1
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
No content selected.