배열 요소에 액세스하려면
포인터를 사용하여 배열 요소에 액세스할 수 있습니다.
C에서
예시
#include <stdio.h>
int main() {
int a[] = { 60, 70, 20, 40 };
printf("%d\n", *(a + 1));
return 0;
} 출력
70
C++에서
예시
#include <iostream>
using namespace std;
int main() {
int a[] = { 60, 70, 20, 40 };
cout<<*(a + 1);
return 0;
} 출력
70
동적 메모리 할당
메모리를 동적으로 할당하기 위해 포인터를 사용합니다.
C에서
예시
#include <stdio.h>
#include <stdlib.h>
int main() {
int i, *ptr;
ptr = (int*) malloc(3 * sizeof(int));
if(ptr == NULL) {
printf("Error! memory not allocated.");
exit(0);
}
*(ptr+0)=1;
*(ptr+1)=2;
*(ptr+2)=3;
printf("Elements are:");
for(i = 0; i < 3; i++) {
printf("%d ", *(ptr + i));
}
free(ptr);
return 0;
} 출력
Elements are:1 2 3
C++에서
예시
#include <iostream>
#include <stdlib.h>
using namespace std;
int main() {
int i, *ptr;
ptr = (int*) malloc(3 * sizeof(int));
if(ptr == NULL) {
cout<<"Error! memory not allocated.";
exit(0);
}
*(ptr+0)=1;
*(ptr+1)=2;
*(ptr+2)=3;
cout<<"Elements are:";
for(i = 0; i < 3; i++) {
cout<< *(ptr + i);
}
free(ptr);
return 0;
} 출력
Elements are:1 2 3
참조로 함수에 인수 전달
포인터를 사용하여 함수에서 참조로 인수를 전달하여 효율성을 높일 수 있습니다.
C에서
예시
#include <stdio.h>
void swap(int* a, int* b) {
int t= *a;
*a= *b;
*b = t;
}
int main() {
int m = 7, n= 6;
swap(&m, &n);
printf("%d %d\n", m, n);
return 0;
} 출력
6 7
C++에서
예시
#include <iostream>
using namespace std;
void swap(int* a, int* b) {
int t= *a;
*a= *b;
*b = t;
}
int main() {
int m = 7, n= 6;
swap(&m, &n);
cout<< m<<n;
return 0;
} 출력
67
연결 목록, 트리와 같은 데이터 구조를 구현하기 위해 포인터도 사용할 수 있습니다.