노트

c++ 배열의 음수 인덱스

tose33 2021. 3. 9. 20:13

이 문제(tose33.tistory.com/101) 를 풀면서 배열의 음수 인덱스에 대해 찾아봤다.

 

stackoverflow.com/questions/47170740/c-negative-array-index

 

C++ negative array index

I alloced an int array of 3 elements, and thought of this code below: int a[3]; for(int i = -2; i < 3; ++i){ a[i] = i; cout<<a[i]<<" ";="" }="" here's="" its="" output:="" -2="" -1="" 0="" 1="" 2="" ...<="" p=""> </a[i]<<">

stackoverflow.com

이 글을 보면 c++ has no array bound check라고 한다.

array bound check란건 배열의 인덱스 범위를 확인하는것이다. 예를들어

string arr[] = {"a", "b", "c", "d"};

cout << arr[17];

이런 코드가 있다면 배열에 17번째는 out of bound이기 때문에 에러를 출력하는것이다.

 

그런데 c++에는 이런 에러를 체크하는 기능이 없기 때문에

int a[3];
for(int i = -2; i < 3; ++i){
    a[i] = i; 
    cout<<a[i]<<" ";
}

이 코드는 원래라면 에러가 나야하지만

-2 -1 0 1 2 

를 출력하게 되고, 이런 코드를 사용한다면 undefined behaviour로 이어진다. 

 

따라서 배열의 음수 인덱스를 사용할수는 있겠지만, 그게 올바른 사용법은 아니라는 뜻인것 같다. 

사용한다면 배열 a[i]는 *(a + i) 를 나타냄으로, 포인터를 이용해서 적절히 배열과 포인터를 생성해서 사용해야 할 것 같다.