1

How is the array accessing values at indexes that are larger than its width. I thought when you go over the size limit it would throw a segfault error.

#include <iostream>

int main(){

    const int len = 3;
    const int wid = 3;

    int arr[len][wid];

    int count = 1;
    // assigns array to numbers 1 - 9
    for(int i =0;i < len;i++){
        for(int j =0;j< wid;j++){
            arr[i][j] = count++;
        }
    }
    
    int index = 0;
    // prints out the array
    while(index < 9){
        std::cout << arr[0][index++] << " "; // how is it accessing space that wasn't allocated? index++
    }
    std::cout << std::endl;

}
David C. Rankin
  • 81,885
  • 6
  • 58
  • 85
thien pham
  • 11
  • 1
  • Welcome to SO! When you go over the size limit, behavior is undefined. Your computer might explode or maybe you accidentally get the correct output. Who knows. – ggorlen Aug 29 '20 at 00:41
  • `int arr[len][wid];` is Non-Standard and only available by compiler extension. Also, recall a 2D array in C/C++ (not including the STL container) are arrays of 1D arrays. So you have `len` arrays of `wid` integers. Your last valid column index is `wid-1`. – David C. Rankin Aug 29 '20 at 00:45

1 Answers1

0

std::cout << arr[0][index++] << " "; // how is it accessing space that wasn't allocated? index++

You can't just change from 2D array to 1D array that way, even though the total number of items are the same (9).

It looks like your purpose is just to print out the input array, you may just want to loop through the 2D array index the way you did when you input it:

So instead of this:

// prints out the array
while(index < 9){
    std::cout << arr[0][index++] << " "; // out of bound access - undefined behaviour (crash or worse)
}

Do this:

for (int i = 0; i < len; i++)
{
    for (int j = 0; j < wid; j++)
    {
        cout << arr[i][j] << ' ';
    }
}
artm
  • 17,291
  • 6
  • 38
  • 54
  • 1
    @thienpham rather than crash, the proper term to use is [Undefined Behaviour](https://en.cppreference.com/w/cpp/language/ub). UB is hated and feared because there are no rules. Maybe you get what you expect. Maybe you don't get what you expect. Maybe you get something close enough that you don't know its wrong until [your boss is onstage at Comdex](https://www.youtube.com/watch?v=73wMnU7xbwE). Your only real defense against UB is to not do it. Fortunately [there are tools](https://clang.llvm.org/docs/UndefinedBehaviorSanitizer.html) that can sometimes help you detect what you've missed. – user4581301 Aug 29 '20 at 00:57
  • @user4581301 good advice – artm Aug 29 '20 at 01:00