본문 바로가기
C and C++/C and C++ Examples

[C++ Example] 포인터(Pointer)를 활용한 간단한 배열 값의 증가 예제코드

by Henry Cho 2023. 10. 13.
728x90

포인터(Pointer)를 활용한 간단한 배열 값의 증가 예제코드

포스트 난이도: HOO_Intern


# Example Code

이번 포스트에서는 포인터의 가장 기본적인 기능을 활용하여 배열의 elements들이 증가하는 것을 살펴볼 수 있다. 우선 void function을 사용해서 addNum()과 display()라는 기능을 만들어준다. addNum은 배열 안의 값, 즉 원소들을 증가시켜 주는 역할을 수행하고 display() 기능에서는 포인터를 활용해서 변화된 배열 원소들을 출력해 주는 역할을 수행한다. 여기서 addNum을 통해서 배열 안의 원소 값을 증가시킬 수 있는 범위를 지정할 수 있고 display()에서는 원하는 배열 원소까지 만을 출력할 수 있도록 설정이 가능하다.

Figure1의 첫번째 예제코드 결과를 살펴보면, 우선 numbers []라는 배열을 지정해 주었고, 그 뒤에 addNum에서 3번째까지의 원소만을 1씩 증가시켜 주도록 설정하였다. 또한 display는 9번째까지 원소가 출력되도록 설정해 주었기 때문에 모든 배열의 원소가 출력되는 걸 볼 수 있다. 따라서 9개의 원소가 모두 출력이 되지만 1,2,3에 해당하는 원소들만 1씩 증가된 결과를 볼 수 있다.

#include <iostream>
using namespace std;

// Function to add 1 to each element in the range [i, j)
void addNum(int* i, int* j)
{
    // For loop through the range
    for (int* count = i; count < j; count++)
    {
        // Increment the value pointed to by 'count'
        (*count)++;
    }
}

// Function to display elements in the range [i, j)
void display(const int* i, const int* j)
{
    // For loop through the range
    for (const int* count = i; count < j; count++)
    {
        cout << *count << endl;
    }
}

// Main block
int main()
{
    // Initialize an array of integers
    int numbers[] = {1,2,3,4,5,4,3,2,1};
    // Call the addNum function
    addNum(numbers, numbers + 3); 
    // Call the display function to print elements
    display(numbers, numbers + 9);

    return 0;
}

Figure1. Result of Example Code 1


만약에 display()와 addNum()의 설정 조건을 변경해줄 경우 결과는 다르게 출력될 수 있다. 예를 들어서 addNum()에 9개의 원소가 모두 1씩 증가하도록 설정하고 display()에 5개의 원소만 출력되도록 설정한다면 첫 번째 원소부터 5번째 원소까지 1씩 증가된 값으로 출력이 되지만 나머지 뒤의 원소들은 1씩 값이 증가했다 할지라도 실제로 출력은 되지 않는 걸 살펴볼 수 있다.


#include <iostream>
using namespace std;

// Function to add 1 to each element in the range [i, j)
void addNum(int* i, int* j)
{
    // For loop through the range
    for (int* count = i; count < j; count++)
    {
        // Increment the value pointed to by 'count'
        (*count)++;
    }
}

// Function to display elements in the range [i, j)
void display(const int* i, const int* j)
{
    // For loop through the range
    for (const int* count = i; count < j; count++)
    {
        cout << *count << endl;
    }
}

// Main block
int main()
{
    // Initialize an array of integers
    int numbers[] = {1,2,3,4,5,4,3,2,1};
    // Call the addNum function
    addNum(numbers, numbers + 9); 
    // Call the display function to print elements
    display(numbers, numbers + 5);

    return 0;
}

Figure2. Result of Example Code 2


# github link

https://github.com/WhoisHOO/HOOAI/blob/main/C%20Examples/increment_array_pointer


728x90

댓글