1
int main()
{
    int n[] = {2};
    cout <<n[1] << endl;

    return 0;
}

In this code, I get some numbers,also for n[2],n[3] etc. I got ë for a string array and @ for a char array. I don't think it is the memory location so what is this?

Crazy_Boy53
  • 241
  • 2
  • 4
  • 10

1 Answers1

4
int n[] = {2};

Here you are declaring an array with one element. So now n[0] is 2. That's the only element, so everything else is out of bounds. Therefore this here:

cout <<n[1] << endl;

Is undefined behavior, because you're accessing the second element, which doesn't exist. Remember, array indexing starts at 0, so element 0 is the first one and 1 is the second one.

So why does it print a rubbish value, then? Since it's undefined behavior, there's no guarantee for what it does, but what's most likely going to happen is that it's calculating the respective memory location and prints the data at the resulting address, interpreted as int. That usually results in some rubbish value.

Blaze
  • 16,736
  • 2
  • 25
  • 44