C++

C++ 포인터 응용

김구티2 2024. 5. 17. 21:53

C의 포인터는 다른 변수의 메모리 주소를 저장하는 데 사용되는 변수다. 포인터를 사용하면 메모리를 효율적으로 관리할 수 있으므로 프로그램을 최적화할 수 있다. 이 글에서는 C의 포인터의 주요 응용 분야에 대해 기술한다.

 

C 프로그래밍 언어에서 포인터의 주요 응용은 다음과 같다.

1. Passing Arguments by Reference

참조에 의해 인수를 전달하는 것은 두 가지 목적을 수행한다.

① 다른 함수의 변수 수정 목적

 

아래 예시는 두 숫자를 교환하여 포인터를 사용하는 방법을 보여준다:

// C program to demonstrate that we can change
// local values of one function in another using pointers.

#include <stdio.h>

void swap(int* x, int* y)
{
     int temp = *x;
     *x = *y;
     *y = temp;
}

int main()
{
     int x = 10, y = 20;
     swap(&x, &y);
     printf("%d %d\n", x, y);
     return 0;
}

 

출력:

20 10

 

② 효율 목적

아래 예시는 효율적인 코드 작성을 위한 포인터 사용을 보여준다:

#include <stdio.h>

// function to print an array by passing reference to array
void printArray(int* arr, int n)
{
     // here array elements are passed by value
     for (int i = 0; i < n; i++) {
          printf("%d ", arr[i]);
     }
}

int main()
{
     int arr[5] = { 1, 2, 3, 4, 5 };
     printArray(arr, 5);
     return 0;
}

 

출력:

1 2 3 4 5

2. For Accessing Array Elements

컴파일러는 내부적으로 배열 요소에 접근하기 위해 포인터를 사용한다. 또한, 이러한 포인터를 사용하여 주어진 배열의 요소에 접근하고 수정할 수 있다.

아래 예시에서는 배열의 요소에 액세스하기 위한 포인터 사용을 보여준다:

// C program to demonstrate that compiler
// internally uses pointer arithmetic to access
// array elements.

#include <stdio.h>

int main()
{
     int arr[] = { 100, 200, 300, 400 };

     // Compiler converts below to *(arr + 2).
     printf("%d ", arr[2]);

     // So below also works.
     printf("%d\n", *(arr + 2));

     return 0;
}

 

출력:

300 300

3. To Return Multiple Values

C의 함수는 단일 값만 반환할 수 있지만, C 함수에서 여러 값을 반환하기 위해 포인터를 사용할 수 있다.

아래 예시에서는 포인터를 사용하여 숫자의 제곱근과 제곱근을 반환하는 포인터 사용법을 보여준다:

// C program to demonstrate that using a pointer
// we can return multiple values.

#include <math.h>
#include <stdio.h>

void fun(int n, int* square, double* sq_root)
{
     *square = n * n;
     *sq_root = sqrt(n);
}

int main()
{

     int n = 100;
     int sq;
     double sq_root;
     fun(n, &sq, &sq_root);

     printf("%d %f\n", sq, sq_root);
     return 0;
}

 

출력:

10000 10

4. For dynamic memory Allocation

포인터를 사용하여 메모리를 동적으로 할당할 수 있다. 동적으로 할당된 메모리의 장점은 명시적으로 삭제하기 전까지는 삭제되지 않는다는 것이다.

다음 예시는 메모리를 동적으로 할당하기 위한 포인터 사용을 보여준다:

// C program to dynamically allocate an
// array of given size.

#include <stdio.h>
#include <stdlib.h>
int* createArr(int n)
{
     int* arr = (int*)(malloc(n * sizeof(int)));
     return arr;
}

int main()
{
     int* pt = createArr(10);
     return 0;
}

728x90