int *a, c; -> a는 포인터 변수, c는 그냥 변수
int b = 6;
int* a;
cout << *a; // *a 는 포인터 변수 a가 가리키는 값
cout << &b; // b의 주소 출력
new, delete 연산자
#include <iostream>
using namespace std;
int main() {
int *P = new int; // new 연산자는 지정한 자료형 만큼의 메모리를 가지고 있는 블록의 주소를 반환
// c의 동적 메모리 할당과 비슷
// int는 4byte
delete p; // 메모리 다른 프로그램이 쓸 수 있게 다시 돌려줌, c에서 동적메모리 할당 후 free 해주듯이
// new[]를 사용할 경우 delete[]로 해제
return 0;
}
포인터 배열
// c언어에서
#include <stdio.h>
int main(void)
{
int a[] = { 10, 20, 30, 40, 50 };
int* p;
p = a;
printf("a[0]=%d a[1]=%d a[2]=%d \n", a[0], a[1], a[2]); // -> 10 20 30
printf("p[0]=%d p[1]=%d p[2]=%d \n\n", p[0], p[1], p[2]); // -> 10 20 30
return 0;
}
// c++에서
#include <iostream>
using namespace std;
int main() {
double* p = new double[3]; // double형 데이터 3개를 저장할 수 있는 공간, p를 배열 이름처럼 취급
p[0] = 0.1;
p[1] = 0.2;
p[2] = 0.3;
cout << "p[1]는" << p[1] << endl;
p = p + 1; // double byte 수 만큼 건너뜀
cout << "p[0]는" << p[0] << " ";
cout << "p[1]는" << p[2] << endl; // p[2]는 쓰레기값
p = p - 1;
delete[] p;
return 0;
}
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#define SIZE 20
using namespace std;
int main() {
char a[SIZE];
char* p;
cout << "입력 : ";
cin >> a;
p = new char[strlen(a) + 1]; // strlen '\0' 빼고 길이 셈
strcpy(p, a);
cout << a << " " << (int*)a << endl;
cout << p << " " << (int*)p << endl;
}
728x90
'c++ 기초' 카테고리의 다른 글
10) 반복문, 중첩 배열 (0) | 2024.12.28 |
---|---|
9) new 이용 동적 구조체 (0) | 2024.12.28 |
7) 공용체, 열거체 (0) | 2024.12.28 |
6) 구조체 (0) | 2024.12.28 |
5) 배열 (0) | 2024.12.27 |