C++

C++ 배열 파라미터의 크기를 프린트하는 방법

김구티2 2024. 5. 29. 19:55

여기서는 배열 파라미터의 크기를 계산하는 방법에 대해 기술하도록 한다.

 

예시:

// A C++ program to show that it is wrong to
// compute size of an array parameter in a function
#include <iostream>
using namespace std;

void findSize(int arr[]) 

     cout << sizeof(arr) << endl; 
}

int main()
{
     int a[10];
     cout << sizeof(a) << " ";
     findSize(a);
     return 0;
}

 

출력:

40   8

 

위의 출력은 정수의 크기가 4바이트이고 포인터의 크기가 8바이트인 것이다.


main() 안에 있는 cout 문은 40을 출력하고 findSize() 안에 있는 cout 문은 8을 출력한다. 왜 서로 값이 다를까? 이 출력이 다른 이유는 배열이 항상 함수에서 포인터를 전달하기 때문이다. 따라서 findSize(int arr[])과 findSize(int *arr)는 정확히 같은 의미다. 따라서 findSize() 안에 있는 cout 문은 포인터의 크기를 출력한다.

 

그렇다면 함수에서 배열의 크기를 어떻게 찾을 수 있을까?

 

우리는 배열에 대한 참조(reference to the array)를 전달할 수 있다.

 

예시:

// A C++ program to show that we can use reference to
// find size of array
#include <iostream>
using namespace std;

void findSize(int (&arr)[10])
{
     cout << sizeof(arr) << endl;
}

int main()
{
     int a[10];
     cout << sizeof(a) << " ";
     findSize(a);
     return 0;
}

 

출력:

40   40

 

그런데 여기서는 배열 파라미터의 하드코딩된 크기를 사용했기 때문에 위의 프로그램은 그다지 추천되지 않는다.

 

더욱 나은 방식은 다음과 같다. 하드코딩된 크기 대신 템플릿을 사용해 함수를 정의할 수 있다.

 

예시:

// A C++ program to show that we use template and
// reference to find size of integer array parameter
#include <iostream>
using namespace std;

template <size_t n>
void findSize(int (&arr)[n])
{
     cout << sizeof(int) * n << endl;
}

int main()
{
     int a[10];
     cout << sizeof(a) << " ";
     findSize(a);
     return 0;
}

 

출력:

40   40

 

우리는 제네릭(Generic) 함수도 만들 수 있다.

 

예시:

// A C++ program to show that we use template and
// reference to find size of any type array parameter
#include <iostream>
using namespace std;

template <typename T, size_t n>
void findSize(T (&arr)[n])
{
     cout << sizeof(T) * n << endl;
}

int main()
{
     int a[10];
     cout << sizeof(a) << " ";
     findSize(a);

     float f[20];
     cout << sizeof(f) << " ";
     findSize(f);
     return 0;
}

 

출력: 

40   40
80   80

 

다음 단계는 동적으로 할당된 배열의 크기를 프린트하는 것이다.


예시(CPP):

#include <iostream>
#include <cstdlib>
using namespace std;

int main()
{
     int *arr = (int*)malloc(sizeof(int) * 20);
     return 0;
}

 

728x90