1. 포인터
int = 정수값 보관 변수
float = 실수값 보관 변수
포인터 = 주소값 보관 변수
포인터 타입의 크기
64비트 컴퓨터들은 주소값 크기가 64비트
-> 포인터는 메모리상에 위치한 특정 데이터의 (시작)주소값을 보관하는 변수이므로 포인터타입 크기는 항상 64비트?
-> 맞음. 포인터 타입 크기는 뭘 가리키고 있냐가 아니라 그 cpu가 몇 비트짜리냐에 의해 정해짐
포인터 선언
*를 붙여서 포인터를 정의
// pointer p is pointing the int type data
// pointer p holds the address where the value lives
int* p;
int *p;
포인터 할당
&를 붙여서 어떤 데이터가 저장된 곳의 주소값을 얻어낼 수 있음
p = &x; // p points to x
역참조
포인터에 애스터리스크를 붙여주면 그 포인터가 가리키고 있는 곳에 저장된 값을 가져올 수 있음
int result = *p; //get value at pointer
예제
x가 메모리 0x100번지에 있다고 하자
#include <stdio.h>
int main() {
int x = 10;
int* p = &x; // p points to x
printf("%d", x); // prints value of x
printf("%d", *p); // *p means "value at p", so also 10
printf("%p", &x); // prints address of x
printf("%p", p); // p stores the same address as &x
return 0;
}
포인터 사용 이유
- 함수 호출을 통해 특정 변수의 값을 변경하기 위해
- 배열, 동적 메모리 생성하기 위해
- 문자열 작업을 하기 위해(?)
- 빠르고 낮은 수준의 컨트롤을 위해...?
문제1
아래와 같이 값이 주어졌을 때, *(p+1), *p+1를 구하시오.
int arr[] = {10, 20, 30};
int* p = arr;
p라는 포인터는 arr[0]의 주소를 보관하고 있음. arr[0]의 주소가 0x100이라면
p = 0x100
*p = 0x100이 가리키고 있는 곳 = 10
*(p+1) = 0x101이 가리키고 있는 곳 = 20
*p+1 = 10+1 = 11
문제2
답:42
*p means 'value at address p'
int a = 42;
int* p = &a;
printf("%d\n", *p); // ?
문제3
답:3
p points to arr[0].
*(p+2) means 'value at arr[2]=3'
int arr[] = {1, 2, 3, 4};
int* p = arr;
printf("%d\n", *(p + 2)); // ?
문제4
답:7
*p means 'value at arr[0]=5'
*p+2 means 5+2=7
int arr[] = {5, 10, 15};
int* p = arr;
printf("%d\n", *p + 2); // ?
문제5
답:200
arr+1 points to arr[1]
*p means 'value at arr[1]=200'
int arr[] = {100, 200, 300};
int* p = arr + 1;
printf("%d\n", *p); // ?
문제6
답:4
p points to arr[0]
++p points to arr[1]
so, *p means 'value at arr[1]=4'
int arr[] = {2, 4, 6, 8};
int* p = arr;
printf("%d\n", *(++p)); // ?
포인터 할당
You can assign one pointer to another if they have the same type.
When you do that, you're copying the address, not the data.
2. 입력변수
C에서 입력변수는 값에 의해 전달(pass by value)됨
void decompose(double number, long out_int_part, double out_frac_part)
{
out_int_part = (long) number; /* number의 소수부를 없앤다 */
out_frac_part = number - (double) out_int_part;
}
decompese(3.14, int_part, frac_part);
1. 3.14라는 '값'이 number에, int_part의 '값'이 out_int_part에, frac_part의 '값'이 out_frac_part에 복사되어 전달됨
2. 그리고 함수가 실행된 후 out_int_part, out_frac_part에 결과값이 할당된다.
3. 그러나 int_part, frac_part값이 바뀌지는 않는다..
입력변수 변환
C는 함수 호출 시 입력변수의 형이 매개변수 형과 같지 않아도 된다.
컴파일러가 호출 이전에 원형을 봤다면 각 입력변수 값은 이에 대응하는 매개변수의 값에 할당할 때와 동일하게 암시적 변환이 일어난다.
예) int 입력변수가 double을 받는 함수에 전달되면 입력변수는 double이 자동으로 형변환된다.
'정글' 카테고리의 다른 글
| 포인터.. 왜 쓸까? (2) | 2025.04.18 |
|---|---|
| Data-Structures Binary Search Tree Q4 - Post Order Iterative 풀이 (2) | 2025.04.17 |
| [정글] c언어 특강 (2) | 2025.04.16 |
| [C언어] 기초 정리(1) - Null문/형 변환/형 정의/배열 (0) | 2025.04.11 |
| [정글/회고] 알고리즘 특강 (0) | 2025.03.19 |