1ํ•™๋…„ (2023)/C ์–ธ์–ด

[C] Study: ๋™์  ๋ฉ”๋ชจ๋ฆฌ - (3) ๊ตฌ์กฐ์ฒด์˜ ๋™์  ์ƒ์„ฑ์„ ํ•ด๋ณด์ž

waterproof 2023. 8. 19. 16:08

 

 

 


 ๊ตฌ์กฐ์ฒด๋ฅผ ์ €์žฅํ•  ์ˆ˜ ์žˆ๋Š” ๊ณต๊ฐ„๋„ ๋‹ค์Œ๊ณผ ๊ฐ™์ด ํ• ๋‹น๋ฐ›์„ ์ˆ˜ ์žˆ๋‹ค.

 

 ๋งŒ์•ฝ ๊ตฌ์กฐ์ฒด์˜ ๋ฐฐ์—ด์ด ํ•„์š”ํ•˜๋ฉด ๊ตฌ์กฐ์ฒด์˜ ํฌ๊ธฐ์—๋‹ค ํ•„์š”ํ•œ ๊ฐœ์ˆ˜๋ฅผ ๊ณฑํ•ด์ฃผ๋ฉด ๋œ๋‹ค.

 

 ์•„๋ž˜์˜ ํ”„๋กœ๊ทธ๋žจ์—์„œ๋Š” ์ฑ…์„ ํ‘œํ˜„ํ•˜๋Š” ๊ตฌ์กฐ์ฒด๋ฅผ ์ •์˜ํ•˜๊ณ  ๊ตฌ์กฐ์ฒด์˜ ๋ฐฐ์—ด์„ ๋™์ ์œผ๋กœ ์ƒ์„ฑํ•œ๋‹ค.

 

struct Book {
	int number;
	char title[100];
};

struct Book *p;
p = (struct Book *)malloc(2 * sizeof(struct Book));

 

๋™์ ์œผ๋กœ ์ƒ์„ฑ๋œ ๊ตฌ์กฐ์ฒด ๋ฐฐ์—ด์€ ํฌ์ธํ„ฐ๋ฅผ ํ†ตํ•ด์„œ๋งŒ ์ ‘๊ทผํ•  ์ˆ˜ ์žˆ๋Š” ์ ์— ์œ ์˜ํ•˜์ž.

 

p[0]๋Š” ์ฒซ ๋ฒˆ์งธ ๊ตฌ์กฐ์ฒด์ด๊ณ  p[1]์€ ๋‘ ๋ฒˆ์งธ ๊ตฌ์กฐ์ฒด์ด๋‹ค.

 

 

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

struct Book {
	int number;
	char title[100];
};

int main(void)
{
	struct Book *p;
	
    p = (struct Book *)malloc(2 * sizeof(struct Book));

	if (p == NULL) {
		printf("๋ฉ”๋ชจ๋ฆฌ ํ• ๋‹น ์˜ค๋ฅ˜\n");
		exit(1);
	}
    
    p[0].number = 1; // (*p).number = 1
	strcpy(p[0].title, "C Programming");

	p[1].number = 2; // (*p+1).number = 2
	strcpy(p[1].title, "Data Structure");

	free(p);
	return 0;
}

 

ํ”„๋กœ๊ทธ๋žจ ์„ค๋ช…

line 5 - 8: ๊ตฌ์กฐ์ฒด๋ฅผ ์ •์˜ํ•œ๋‹ค. ๊ตฌ์กฐ์ฒด์˜ ๋ฉค๋ฒ„๋Š” ์ •์ˆ˜ํ˜• ๋ณ€์ˆ˜ number์™€ ๋ฌธ์ €ํ˜• ๋ฐฐ์—ด name[]์ด๋‹ค.
line 12: ๊ตฌ์กฐ์ฒด๋ฅผ ๊ฐ€๋ฆฌํ‚ฌ ์ˆ˜ ์žˆ๋Š” ํฌ์ธํ„ฐ ๋ณ€์ˆ˜๋ฅผ ์„ ์–ธํ•œ๋‹ค.
line 14: malloc()์„ ์ด์šฉํ•˜์—ฌ ๊ตฌ์กฐ์ฒด 2๊ฐœ ๋ถ„๋Ÿ‰์˜ ๋ฉ”๋ชจ๋ฆฌ๋ฅผ ๋™์ ์œผ๋กœ ํ• ๋‹น๋ฐ›๋Š”๋‹ค. ์ด ๋ฉ”๋ชจ๋ฆฌ ๋ธ”๋ก์˜ ์‹œ์ž‘ ์ฃผ์†Œ๋ฅผ p์— ๋Œ€์ž…ํ•œ๋‹ค.
line 16: malloc()์ด ๋ฐ˜ํ™˜ํ•œ ๊ฐ’์ด NULL์ธ์ง€๋ฅผ ๊ฒ€์‚ฌํ•œ๋‹ค. NULL์ด๋ฉด ๋ฉ”๋ชจ๋ฆฌ ํ• ๋‹น ์˜ค๋ฅ˜์ด๋ฏ€๋กœ ๋ฉ”์‹œ์ง€๋ฅผ ์ถœ๋ ฅํ•˜๊ณ  exit()๋ฅผ ํ˜ธ์ถœํ•˜์—ฌ ์ข…๋ฃŒํ•œ๋‹ค.
line 21 - 22: ๋™์ ์œผ๋กœ ํ• ๋‹น๋ฐ›์€ ์ฒซ ๋ฒˆ์งธ ๊ตฌ์กฐ์ฒด์— ๋ฐ์ดํ„ฐ๋ฅผ ๋Œ€์ž…ํ•œ๋‹ค.
line 24 - 25: ๋™์ ์œผ๋กœ ํ• ๋‹น๋ฐ›์€ ๋‘ ๋ฒˆ์งธ ๊ตฌ์กฐ์ฒด์— ๋ฐ์ดํ„ฐ๋ฅผ ๋Œ€์ž…ํ•œ๋‹ค.
line 27: ๋™์ ์œผ๋กœ ํ• ๋‹น๋ฐ›์€ ๊ณต๊ฐ„์€ ์‚ฌ์šฉ์ด ๋๋‚˜๋ฉด ํ•ญ์ƒ ์‹œ์Šคํ…œ์— ๋ฐ˜๋‚ฉํ•˜์—ฌ์•ผ ํ•œ๋‹ค. free()๋ฅผ ํ˜ธ์ถœํ•˜์—ฌ malloc()์ด ํ• ๋‹นํ•œ ๊ณต๊ฐ„์„ ๋ฐ˜๋‚ฉํ•œ๋‹ค,