# [C] ํฌ์ธํ„ฐ(Pointer)



ํฌ์ธํ„ฐ : ํŠน์ • ๋ณ€์ˆ˜๋ฅผ ๊ฐ€๋ฆฌํ‚ค๋Š” ์—ญํ• ์„ ํ•˜๋Š” ๋ณ€์ˆ˜


main์—์„œ ํ•œ๋ฒˆ ๋งŒ๋“ค์–ด๋‘” ๋ณ€์ˆ˜ ๊ฐ’์„ ๋‹ค๋ฅธ ํ•จ์ˆ˜์—์„œ ๊ทธ๋Œ€๋กœ ์‚ฌ์šฉํ•˜๊ฑฐ๋‚˜, ๋ณ€๊ฒฝํ•˜๊ณ  ์‹ถ์€ ๊ฒฝ์šฐ๊ฐ€ ์žˆ๋‹ค.

๊ฐ™์€ ์ง€์—ญ์— ์žˆ๋Š” ๋ณ€์ˆ˜๋ผ๋ฉด ์‚ฌ์šฉ ๋ฐ ๋ณ€๊ฒฝ์ด ๊ฐ„๋‹จํ•˜์ง€๋งŒ, ๋‹ค๋ฅธ ์ง€์—ญ์ธ ๊ฒฝ์šฐ์—๋Š” ํ•ด๋‹น ๊ฐ’์„ ์ž„์‹œ ๋ณ€์ˆ˜๋กœ ๋ฐ›์•„ ๋ฐ˜ํ™˜ํ•˜๋Š” ์‹์œผ๋กœ ์ฒ˜๋ฆฌํ•œ๋‹ค.

์ด๋•Œ ํšจ์œจ์ ์œผ๋กœ ์ฒ˜๋ฆฌํ•  ์ˆ˜ ์žˆ๋„๋ก ํฌ์ธํ„ฐ๋ฅผ ์‚ฌ์šฉํ•˜๋Š” ๊ฒƒ!

ํฌ์ธํ„ฐ๋Š” ๋ฉ”๋ชจ๋ฆฌ๋ฅผ ํ• ๋‹น๋ฐ›๊ณ  ํ•ด๋‹น ๊ณต๊ฐ„์„ ๊ธฐ์–ตํ•˜๋Š” ๊ฒƒ์ด ๊ฐ€๋Šฅํ•˜๋‹ค.


์•„๋ž˜์™€ ๊ฐ™์€ ์ฝ”๋“œ๊ฐ€ ์žˆ์„ ๋•Œ๋ฅผ ํ™•์ธํ•ด๋ณด์ž


#include<stdio.h>

int ReturnPlusOne(int n) {
    printf("%d\n", n+1);
	return n + 1;
}

int main(void) {

	int number = 3;
	printf("%d\n", number);

	number = 5;
	printf("%d\n", number);

	ReturnPlusOne(number);
	printf("%d\n", number);

	return 0;
}

[์ถœ๋ ฅ ๊ฒฐ๊ณผ]
3
5
6
5

main์˜ number์™€ function์˜ n์€ ๋‹ค๋ฅธ ๋ณ€์ˆ˜๋‹ค.

์ด์ œ ํฌ์ธํ„ฐ๋กœ ๋ฌธ์ œ๋ฅผ ์ ‘๊ทผํ•ด๋ณด๋ฉด?


#include<stdio.h>

int ReturnPlusOne(int *n) {
	*n += 1;
}

int main(void) {

	int number = 3;
	printf("%d\n", number);

	number = 5;
	printf("%d\n", number);

	ReturnPlusOne(&number);
	printf("%d\n", number);

	return 0;
}

[์ถœ๋ ฅ ๊ฒฐ๊ณผ]
3
5
6

ํฌ์ธํ„ฐ๋ฅผ ํ™œ์šฉํ•ด์„œ ์šฐ๋ฆฌ๊ฐ€ ๊ธฐ์กด์— ์›ํ–ˆ๋˜ ๊ฒฐ๊ณผ๋ฅผ ๊ฐ€์ ธ์˜ฌ ์ˆ˜ ์žˆ๋Š” ๊ฒƒ์„ ํ™•์ธํ•  ์ˆ˜ ์žˆ๋‹ค.


int* p; : intํ˜• ํฌ์ธํ„ฐ๋กœ p๋ผ๋Š” ์ด๋ฆ„์˜ ๋ณ€์ˆ˜๋ฅผ ์„ ์–ธ

p = &num; : p์˜ ๊ฐ’์— num ๋ณ€์ˆ˜์˜ ์ฃผ์†Œ๊ฐ’ ๋Œ€์ž…

printf("%d", *p); : p์— *๋ฅผ ๋ถ™์ด๋ฉด p์— ๊ฐ€๋ฆฌํ‚ค๋Š” ์ฃผ์†Œ์— ์žˆ๋Š” ๊ฐ’์„ ๋‚˜ํƒ€๋ƒ„

printf("%d", p); : p๊ฐ€ ๊ฐ€๋ฆฌํ‚ค๊ณ  ์žˆ๋Š” ์ฃผ์†Œ๋ฅผ ๋‚˜ํƒ€๋ƒ„


#include<stdio.h>

int main(void) {
	
    int number = 5;
    int* p;
    p = &number;
    
    printf("%d\n", number);
    printf("%d\n", *p);
    printf("%d\n", p);
    printf("%d\n", &number);

	return 0;
}

[์ถœ๋ ฅ ๊ฒฐ๊ณผ]
5
5
์ฃผ์†Œ๊ฐ’
์ฃผ์†Œ๊ฐ’

๊ฐ€๋ฆฌํ‚ค๋Š” ์ฃผ์†Œ - ๊ฐ€๋ฆฌํ‚ค๋Š” ์ฃผ์†Œ์— ์žˆ๋Š” ๊ฐ’์˜ ์ฐจ์ด๋‹ค.



# ์ด์ค‘ ํฌ์ธํ„ฐ

ํฌ์ธํ„ฐ์˜ ํฌ์ธํ„ฐ, ์ฆ‰ ํฌ์ธํ„ฐ์˜ ๋ฉ”๋ชจ๋ฆฌ ์ฃผ์†Œ๋ฅผ ์ €์žฅํ•˜๋Š” ๊ฒƒ์„ ๋งํ•œ๋‹ค.


#include <stdio.h>

int main()
{
    int *numPtr1;     // ๋‹จ์ผ ํฌ์ธํ„ฐ ์„ ์–ธ
    int **numPtr2;    // ์ด์ค‘ ํฌ์ธํ„ฐ ์„ ์–ธ
    int num1 = 10;

    numPtr1 = &num1;    // num1์˜ ๋ฉ”๋ชจ๋ฆฌ ์ฃผ์†Œ ์ €์žฅ 

    numPtr2 = &numPtr1; // numPtr1์˜ ๋ฉ”๋ชจ๋ฆฌ ์ฃผ์†Œ ์ €์žฅ

    printf("%d\n", **numPtr2);    // 20: ํฌ์ธํ„ฐ๋ฅผ ๋‘ ๋ฒˆ ์—ญ์ฐธ์กฐํ•˜์—ฌ num1์˜ ๋ฉ”๋ชจ๋ฆฌ ์ฃผ์†Œ์— ์ ‘๊ทผ

    return 0;
}

[์ถœ๋ ฅ ๊ฒฐ๊ณผ]
10

ํฌ์ธํ„ฐ์˜ ๋ฉ”๋ชจ๋ฆฌ ์ฃผ์†Œ๋ฅผ ์ €์žฅํ•  ๋•Œ๋Š”, ์ด์ค‘ ํฌ์ธํ„ฐ๋ฅผ ํ™œ์šฉํ•ด์•ผ ํ•œ๋‹ค.

์‹ค์ œ ๊ฐ’์„ ๊ฐ€์ ธ์˜ค๊ธฐ ์œ„ํ•ด **numPtr2์ฒ˜๋Ÿผ ์—ญ์ฐธ์กฐ ๊ณผ์ •์„ ๋‘๋ฒˆํ•˜์—ฌ ๊ฐ€์ ธ์˜ฌ ์ˆ˜ ์žˆ๋‹ค.




# [์ฐธ๊ณ  ์ž๋ฃŒ]

์ตœ์ข… ์ˆ˜์ • : 12/17/2022, 7:23:59 AM