struct 태그명 {
데이터형 멤버1;
데이터형 멤버2;
...
};
struct content {
char title[40];
int price;
double rate;
};
struct content가 새로운 데이터형이 됨struct content c1;// 방법 1: 선언과 동시에 초기화
struct content c1 = {"Avengers", 11000, 8.8};
// 방법 2: 부분 초기화 (나머지는 0으로 초기화)
struct content c2 = {"Movie", 5000};
// 방법 3: 구조체 변수 간 초기화
struct content c3 = c1;
. (점 연산자)> (화살표 연산자, 포인터용)c1.price = 10000; // 점 연산자
ptr->price = 10000; // 화살표 연산자
struct content arr[] = {
{"Movie1", 5000, 7.5},
{"Movie2", 8000, 8.0},
{"Movie3", 6000, 6.5}
};
arr[i].memberstruct content* ptr = &c1;
ptr->price = 9000; // 포인터를 통한 멤버 접근
(*ptr).price = 9000; // 동일한 표현
const 포인터: 읽기 전용 접근void print_content(struct content c);
void print_content(const struct content* ptr); // 입력용
void modify_content(struct content* ptr); // 수정용
struct point {
int x, y;
};
struct line {
struct point start, end;
};
ln.start.x다음 구조체의 메모리 크기를 계산하고, 그 이유를 설명하시오.
struct student {
char name[20];
int age;
double gpa;
};
풀이:
다음 코드의 출력 결과를 예측하고, 오류가 있다면 수정하시오.
struct book {
char title[30];
int pages;
double price;
};
int main() {
struct book b1 = {"C Programming", 500};
struct book b2;
b2 = {"Data Structure", 400, 35.5}; // 오류!
printf("%s %d %.1f\n", b1.title, b1.pages, b1.price);
return 0;
}
풀이:
{}로 직접 대입 불가strcpy(b2.title, "Data Structure"); b2.pages = 400; b2.price = 35.5;C Programming 500 0.0학생 정보를 저장하는 구조체 배열에서 특정 학생을 찾는 함수를 작성하시오.
struct student {
char name[20];
int id;
double gpa;
};
// 학번으로 학생을 찾는 함수 (반환: 인덱스, 없으면 -1)
int find_student(const struct student arr[], int size, int target_id);
풀이:
int find_student(const struct student arr[], int size, int target_id) {
for (int i = 0; i < size; i++) {
if (arr[i].id == target_id) {
return i; // 찾은 학생의 인덱스 반환
}
}
return -1; // 찾지 못함
}
다음 코드의 출력 결과를 예측하시오.
struct point {
int x, y;
};
int main() {
struct point p1 = {10, 20};
struct point* ptr = &p1;
ptr->x += 5;
(*ptr).y *= 2;
printf("%d %d\n", p1.x, p1.y);
printf("%d %d\n", ptr->x, ptr->y);
return 0;
}
풀이:
15 40 (두 번 동일)다음 두 함수의 차이점을 설명하고, 각각 언제 사용해야 하는지 서술하시오.
// 함수 A
void print_book1(struct book b);
// 함수 B
void print_book2(const struct book* b);
풀이:
다음 구조체에서 사각형의 넓이를 계산하는 함수를 작성하시오.
struct point {
int x, y;
};
struct rectangle {
struct point top_left;
struct point bottom_right;
};
double calc_area(const struct rectangle* rect);
풀이:
double calc_area(const struct rectangle* rect) {
int width = rect->bottom_right.x - rect->top_left.x;
int height = rect->top_left.y - rect->bottom_right.y;
return (double)(width * height);
}
요일을 나타내는 열거체를 정의하고, 주말인지 평일인지 판단하는 함수를 작성하시오.
풀이:
enum weekday {
MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY
};
int is_weekend(enum weekday day) {
return (day == SATURDAY || day == SUNDAY);
}
구조체 사용 시 struct 키워드 누락
content c1; // 오류!
struct content c1; // 올바름
선언 후 {} 직접 대입
struct book b;
b = {"Title", 300}; // 오류!
구조체 변수 직접 비교
if (b1 == b2) // 오류!
// 멤버별로 비교해야 함
배열 멤버 직접 대입
b1.title = b2.title; // 오류!
strcpy(b1.title, b2.title); // 올바름