티스토리 뷰

노트

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) 를 나타냄으로, 포인터를 이용해서 적절히 배열과 포인터를 생성해서 사용해야 할 것 같다.

'노트' 카테고리의 다른 글

c++) 2차원 vector의 user input  (0) 2021.03.12
mac, homebrew 설치 시 /opt/homebrew/bin is not in your PATH. 에러  (0) 2021.03.10
c++) map.find  (0) 2021.02.18
c++) Container  (0) 2021.02.15
c# base 키워드  (0) 2020.11.19
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2025/06   »
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30
글 보관함