2학년 2학기/c언어
11-5장 const struct
kkkkk1023
2024. 11. 11. 11:27
const를 구조체에 사용하는 이유
- 데이터 보호, 가독성, 최적화, 메모리 절약 등 여러 면에서 유용
- 특히 큰 데이터 구조를 전달할 때는 const 포인터가 복사 비용을 줄여 주므로, 메모리 절약 측면에서 유리할 수 있다.
따라서, 값에 의한 호출과 동일한 효과를 내지만 포인터와 const를 사용하는 이유는 값에 의한 호출로 큰 데이터 구조를 전달하면 많은 메모리를 잡아 먹기 때문에 const와 포인터를 사용해서 주소를 전달하지만 원본의 값은 변경하지 못하게 하는 효과를 낼 수 있다. 이렇게 하면 메모리를 절약할 수 있다.
[const struct 사용 예시]
#include <stdio.h>
#include <string.h>
struct student {
int number;
char name[10];
double grade;
};
int equal(const struct student *s1, const struct student *s2) {
if (strcmp((*s1).name, (*s2).name) == 0)
return 1;
else
return 0;
}
int main() {
struct student s1 = { 25, "Mun", 3.92 };
struct student s2 = { 26, "KiM", 3.76 };
printf("%d", equal(&s1, &s2)); // 0
return 0;
}