C 구조체: 전달, 반환, 참조 다루기 마스터하기
C 구조체: 전달, 반환, 참조 다루기
C 프로그래밍에서 구조체는 관련 데이터를 하나의 엔티티로 묶을 수 있게 합니다. 이 가이드는 구조체와 관련된 세 가지 필수 연산인 함수에 전달하기, 함수에서 반환하기, 참조로 조작하기를 안내합니다. 각 섹션에는 간결한 설명과 작동하는 예제가 포함되어 이해를 돕습니다.
함수에 구조체 전달하기
내장 타입처럼 구조체 변수도 함수에 직접 전달할 수 있습니다. 시작하기 전에 C 구조체, C 함수, 사용자 정의 함수를 복습하면 도움이 됩니다.
다음 예제는 struct student를 함수에 전달하여 내용을 출력하는 방법을 보여줍니다.
#include <stdio.h>
struct student {
char name[50];
int age;
};
// 함수 원형
void display(struct student s);
int main() {
struct student s1;
printf("이름 입력: ");
scanf("%[^ ]%%*c", s1.name); // 줄바꿈 전까지 읽기
printf("나이 입력: ");
scanf("%d", &s1.age);
display(s1); // 구조체를 함수에 전달
return 0;
}
void display(struct student s) {
printf("\n정보 출력\n");
printf("Name: %s", s.name);
printf("\nAge: %d", s.age);
}
출력
이름 입력: Bond
나이 입력: 13
정보 출력
Name: Bond
Age: 13
함수에서 구조체 반환하기
함수는 전체 구조체를 반환할 수 있어 데이터 수집과 처리를 깔끔하게 분리할 수 있습니다. 아래 예제는 함수 내부에서 학생 정보를 수집하여 main으로 반환합니다.
#include <stdio.h>
struct student {
char name[50];
int age;
};
// 함수 원형
struct student getInformation();
int main() {
struct student s;
s = getInformation();
printf("\n정보 출력\n");
printf("Name: %s", s.name);
printf("\nAge: %d", s.age);
return 0;
}
struct student getInformation() {
struct student s1;
printf("이름 입력: ");
scanf("%[^ ]%%*c", s1.name);
printf("나이 입력: ");
scanf("%d", &s1.age);
return s1;
}
함수의 반환 타입이 반환하는 구조체와 일치하여 타입 안전성과 명확성을 보장합니다.
구조체를 참조로 전달하기
함수가 구조체를 수정해야 할 때는 주소(포인터)를 전달합니다. 이는 내장 타입을 참조로 전달하는 것과 유사합니다. 다음 예제는 두 복소수를 더하고 결과를 포인터를 통해 저장합니다.
#include <stdio.h>
typedef struct Complex {
float real;
float imag;
} complex;
void addNumbers(complex c1, complex c2, complex *result);
int main() {
complex c1, c2, result;
printf("첫 번째 숫자:\n");
printf("실수부 입력: ");
scanf("%f", &c1.real);
printf("허수부 입력: ");
scanf("%f", &c1.imag);
printf("두 번째 숫자:\n");
printf("실수부 입력: ");
scanf("%f", &c2.real);
printf("허수부 입력: ");
scanf("%f", &c2.imag);
addNumbers(c1, c2, &result);
printf("\nresult.real = %.1f\n", result.real);
printf("result.imag = %.1f", result.imag);
return 0;
}
void addNumbers(complex c1, complex c2, complex *result) {
result->real = c1.real + c2.real;
result->imag = c1.imag + c2.imag;
}
출력
첫 번째 숫자,
실수부 입력: 1.1
허수부 입력: -2.4
두 번째 숫자,
실수부 입력: 3.4
허수부 입력: -3.2
result.real = 4.5
result.imag = -5.6
result가 참조로 전달되므로 addNumbers 내부에서의 변경이 main의 변수에 즉시 반영됩니다.
이 기법들을 마스터하면 구조체의 강력한 기능을 온전히 활용하는 더 모듈화되고 읽기 쉽고 효율적인 C 코드를 작성할 수 있습니다.