노트
c++) 변수 크기의 배열 선언 (int arr[n])
tose33
2021. 4. 29. 21:55
int arr[n] 처럼 배열의 크기를 n, 즉 변수로 선언할수 있을까?
이전부터 c++에서는 안된다고는 알고있었는데 한번 제대로 찾아봤다.
결론은 c++ 에서는 원래는 허용을 안하지만, 일부 컴파일러에서는 허용한다고 한다.
그말은 결국 이런식으로 선언하면 안된다는 말이다.
그렇다면 이런식으로 배열의 크기를 변수로 선언하고 싶으면 어떤 방법이 있을까
1. 동적으로 할당
int n = 10;
int* a = new int[n];
2. 가변적 컨테이너 사용 (vector 등)
int n = 10;
vector<int> a(n);
3. constant(상수) 사용
const int n = 10;
int a[n];
참고:
Array[n] vs Array[10] - Initializing array with variable vs real number
I am having the following issue with my code: int n = 10; double tenorData[n] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; Returns the following error: error: variable-sized object 'tenorData' may not...
stackoverflow.com