Notice
Recent Posts
Recent Comments
Link
«   2025/07   »
1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30 31
Tags
more
Archives
Today
Total
관리 메뉴

문타쿠, 공부하다.

[C언어 코딩 도장] Unit 53. 구조체 배열 사용하기 본문

C언어/C언어 코딩 도장

[C언어 코딩 도장] Unit 53. 구조체 배열 사용하기

개발새발 문타쿠 2023. 12. 8. 01:55

INTRO

구조체 변수를 겁나 많이 선언해야한다면..?

struct Point2D {
	int x;
	int y;
};

struct Point2D p1;
struct Point2D p2;
.
.
.
struct Point2D p100;

이럴 때 사용하는 것이 바로 구조체 배열 선언!

struct Point2D p[100];

 


53.1 구조체 배열 선언하기

#include <stdio.h>

struct Point2D {
	int x;
	int y;
};

int main(void)
{
	struct Point2D p[3];

	p[0].x = 10;
	p[0].y = 20;
	p[1].x = 30;
	p[1].y = 40;
	p[2].x = 50;
	p[2].y = 60;

	printf("p[0]: %d %d\n", p[0].x, p[0].y);
	printf("p[1]: %d %d\n", p[1].x, p[1].y);
	printf("p[2]: %d %d\n", p[2].x, p[2].y);

	return 0;
}


구조체 배열을 선언하는 동시에 초기화 하려면...

#include <stdio.h>

struct Point2D {
	int x;
	int y;
};

int main(void)
{
	struct Point2D p1[3] = { {.x = 10, .y = 20},
				 {.x = 30, .y = 40},
				 {.x = 50, .y = 60} };

	printf("방법 1\n");
	printf("p1[0]: %d %d\n", p1[0].x, p1[0].y);
	printf("p1[1]: %d %d\n", p1[1].x, p1[1].y);
	printf("p1[2]: %d %d\n\n", p1[2].x, p1[2].y);

	struct Point2D p2[3] = { {100, 200}, {300, 400}, {500, 600} };

	printf("방법 2\n");
	printf("p2[0]: %d %d\n", p2[0].x, p2[0].y);
	printf("p2[1]: %d %d\n", p2[1].x, p2[1].y);
	printf("p2[2]: %d %d\n\n", p2[2].x, p2[2].y);

	return 0;
}


53.2 구조체 포인터 배열 선언하기

구조체 요소가 위처럼 한꺼번에 뭉쳐져 있는 배열이 아닌 요소마다 메모리를 할당하고 싶을 수도 있는데, 이때는 '구조체 포인터 배열'을 만들고 malloc() 함수로 각 요소에 메모리를 할당하면 된다.

#include <stdio.h>
#include <stdlib.h>

struct Point2D {
	int x;
	int y;
};

int main(void)
{
	struct Point2D* p[3];

	/* sizeof(struct Point2D*) = 요소(구조체 포인터)의 크기 = int가 2개 = 8바이트
	 * sizeof(p) = 구조체 포인터 배열 p의 전체 크기 = 8바이트가 3개 = 24바이트
	 * sizeof(p) / sizeof(struct Point2D*) = 요소(구조체 포인터)의 개수 = 3개 = p[0], p[1], p[2] */
	// 요소의 개수만큼 반복
	for (int i = 0; i < sizeof(p) / sizeof(struct Point2D*); ++i)
		// 각 요소에 구조체 크기만큼 메모리 할당
		p[i] = malloc(sizeof(struct Point2D));

	p[0]->x = 10;
	p[0]->y = 20;
	p[1]->x = 30;
	p[1]->y = 40;
	p[2]->x = 50;
	p[2]->y = 60;

	printf("p[0]: %d %d\n", p[0]->x, p[0]->y);
	printf("p[1]: %d %d\n", p[1]->x, p[1]->y);
	printf("p[2]: %d %d\n", p[2]->x, p[2]->y);

	for (int i = 0; i < sizeof(p) / sizeof(struct Point2D*); ++i)
		free(p[i]);

	return 0;
}