24. const와 포인터 (2)

P4·2023년 6월 15일
0
post-thumbnail

포인터 변수를 다룰때 2가지 경우의 수

  • *pInt = 10; 이런식으로 포인터 변수가 가리키는 대상의 값을 바꾸거나?

  • pInt = nullptr; 이런식으로 포인터 변수 자체에 담긴 주소를 다룰 수도 있음

#include <stdio.h>

int main(void)
{
	volatile const int cint = 100;

	int* test_cint = (int*)&cint;

	*test_cint = 200;

	printf("%d", cint);

	////////////////////////////////////////////////////////

	// const와 포인터
	int a = 0;
	int b = 0;
	int* pInt = &a;

	const int* pConstInt = &a;
	// *pConstInt = 100;

	// const와 포인터 2번째
	int* const pIntConst = &a;
	*pIntConst = 999;
	// pIntConst = &b;

    const int* const pConstIntConst = nullptr;

	return 0;
}

  • const int* pConstInt = &a; = 값 자체

    • 저기서 *pConstInt = 100; 이 부분은 가리키는 값이 상수인 것으로 식이 바꿀수있는 l-value여야 한다는 오류가 뜸

  • int* const pIntConst = &a; = 포인터 변수 자체

    • pIntConst = &b; 이 부분은 포인터 변수 자체가 상수인 것으로 마찬가지로 l-value여야 한다는 오류가 뜸

  • const int* const pConstIntConst = nullptr;

    • 가리키는 값도, 변수 자체도 전부 상수
profile
지식을 담습니다.

0개의 댓글