void save_address(void)
{
int num = 10;
int* num_address = #
}
void print_value(void)
{
int score = 100;
int* pointer = &score;
printf("%d", *pointer);
}
void print_argument(float* arg)
{
printf("%f", *arg);
}
/*메인 함수*/
float pi;
print_value( );
pi = 3.14f;
print_argument(&pi);
참조
- 포인터가 이미 하고 있음.
- 어떤 변수의 값을 직접 가져다 쓰는게 아니라 그게 어디 있다 참조함
- 즉, 값이 어디에 있는지 가리키고 있는 것
역 참조
- 주소로 직접 가서 거기 저장 되어있는 값에 접근
int* add(const int op1, const int op2)
{
int result = op1 + op2;
return &result;
}
int main(void)
{
int* result;
result = add(10, 20);
return 0;
}
포인터를 반환해도 되는 경우…!
전역 변수
파일 속 static 전역 변수
함수 내 static 변수
힙 메모리에 생성한 데이터
언제 포인터를 반환할까?
도우미 함수 안에 생성한 변수를 다른 함수에서 사용하고자 할 때
단, 일반 지역변수면 안됨 (함수호출이 끝나면 스택에서 사라짐)
함수 안에서 대용량을 데이터를 생성하고 그걸 반환하고자 할 때
이 경우에는 데이터를 스택 메모리가 아니라 힙 메모리라는 곳에 생성함
void do_something()
{
int number;
int* num_ptr = &number;
/* 코드 생략 */
num_ptr = NULL;
}
#define NULL ((void*)0)
int* ptr;
if (ptr == NULL) {
}
if (ptr != NULL){
}
#define PRICE (2)
void increase_price(int* current_price)
{
if (current_price != NULL) {
*current_price += PRICE;
}
}
or_null을 붙인다.
int get_score(const char* const student_id_or_null)
{
/* 코드 생략 */
}
#include<assert.h>
#define PRICE (2)
void increase_price(int* current_price)
{
assert(current_price != NULL);
*current_price += PRICE;
}
#### NULL은 골칫덩어리다 : 반환값 편
- NULL을 반환할 때도 마찬가지
- 기본적으로 안 함 (NULL을)
- 반환을 해야 한다면 함수 이름에 NULL을 반환하는 것을 명시할 것
```C
const char* get_name_or_null(const int id)
{
/* 코드 생략*/
return NULL;
}
void do_something(void)
{
int* ptr = NULL; /* 당장 사용하지 않으므로 널 포인터로 초기화 */
/* 코드 생략 */
ptr = &g_moster_count; /* 전역 변수의 주소 저장 */
/* 코드 생략*/
}
void do_something(void)
{
/*다른 변수 생략 */
int* ptr = #
/* 코드 200줄 */
ptr = NULL;
/* 코드 500줄 */
if (ptr != NULL){
*ptr = 100;
}
}