2.1 포인터
Def) 포인터(Pointer)
포인터란 값을 저장하는 변수가 아니라 주소값을 저장하는 변수이다. 값은 저장할 수 없고 주소만 저장할 수 있다.
Note) 새로운 자료형 " 포인터는 주소값을 지정하는 변수" (자료형) (변수명) = 값;
- 기존 자료형 ( int/ char/ long long int/ float/ double/ ... ) -> int num = 정수값;
- 포인터 자료형 ( int*/ char*/ long long int*/ float*/ double*/ ... ) -> int* pNum = 정수값이 저장된 주소값;
- 역참조 연산자* (Asterisk): 피연산자로 주소값은 가지는 연산자.
해당 주소값에 있는 변수(or 값)을 반환한다.
Ex)
<hide/>
#include <stdio.h>
int main()
{
int n = 100;
int* ptr;
ptr = &n;
printf("%d\n", n);
printf("%d\n", *ptr);
return 0;
}
2.2 포인터 연산 1
- ++*p: "*"부터 진행하고 ++를 연산. 연산자 우선 순위가 같은 경우 결합성에 따라 연산.
p가 가리키는 곳의 값을 1증가한다.
<hide/>
#include <stdio.h>
int main()
{
int x = 10;
int* p;
p = &x;
printf("%d\n", x );
printf("%d\n", ++*p );
printf("%d\n", x );
return 0;
}
2.3 포인터 연산 2
Ex)
<hide/>
#include <stdio.h>
int main()
{
int ar[5] = { 1, 2, 3, 4, 5};
int* p = ar;
printf("%d\n", p); // &ar[0] 주소 출력
printf("%d\n", *p);
printf("%d\n", *p++);
printf("%d\n", *p);
return 0;
}
2.4 포인터 & 배열
Ex)
<hide/>
#include <stdio.h>
int main()
{
int ar[5] = { 1, 2, 3, 4, 5};
int* p = ar;
printf("%d\n", ar); // ar배열의 첫 번째 주소값
printf("%d\n", p ); // 포인터 변수 p가 가리키는 주소값
printf("%d\n", *p );
printf("%d\n", ar[0]);
printf("%d\n", p[0]);
return 0;
}
2.5 Call by address(주소에 의한 전달)
Def) add(&x) : x의 주소를 전달한다는 의미에서 주소에 의한 전달 방식 이라고 함.
"&": address(주소)
call by address의 중요 문법: 전달받은 포인터가 가리키는 곳의 변수값을 함수에서 변경 가능.
Ex)
<hide/>
#include <stdio.h>
void add(int* x)
{
*x = 100;
printf("%d\n", *x);
}
int main()
{
int x;
x = 2;
printf("%d\n", x );
add(&x);
printf("%d\n", x );
return 0;
}
2.6 다중 포인터
Def) 포인터 변수 p의 주소를 저장하기 위해서는 2중 포인터를 사용해야 한다. 만약 pp의 주소를 저장하려면 3중 포인 터 (int ***ppp )를 사용해야 한다.
Ex)
<hide/>
#include <stdio.h>
int main()
{
int x = 10;
int*p = &x;
int**pp = &p;
printf("%d\n", x );
printf("%d\n", *p );
printf("%d\n", **pp );
return 0;
}
2.7 함수 포인터 1
Note) 함수 포인터를 선언할 때는 리턴형과 인자만 정확하게 작성하면 된다.
<hide/>
#include <stdio.h>
void sayHello(void); //sayHello is function that takes void parameters and returns void.
int main()
{
void (*pf)(void); // pf is pointer to function that takes void paramater and returns void.
pf = sayHello; // 함수 포인터 pf에 sayHello를 대입, sayHello는 힘수 시작 주소
pf(); //함수 포인터를 통한 함수 호출
return 0;
}
void sayHello(void)
{
printf("Hello, world");
return;
}
2.8 함수 포인터 2
Ex)
<hide/>
#include <stdio.h>
int add(int op1, int op2); // add is function that takes two int parameters and returns int.
int main(void)
{
int (*pf)(int , int); //pf is pointer to funtion that two int parameters and returns int.
int res;
pf = add; //함수 포인터 pf에 add를 대입. add는 함수의 시작 주소
res = pf(2, 5); //함수 포인터 pf를 통한 호출.
printf("%d", res);
return 0;
}
int add(int op1, int op2)
{
return op1 + op2;
}
'컴퓨터 과학 > C Language' 카테고리의 다른 글
Chapter 03. 구조체 정의 (0) | 2022.02.01 |
---|---|
Chapter 01. 함수(Function) (0) | 2022.01.30 |
2022-01-27 재귀함수 (0) | 2022.01.28 |
2022-01-26 구조체 할당 (0) | 2022.01.27 |
2022-01-24 포인터 연습 (0) | 2022.01.25 |