Why is the output extra in this case?

+1 Raghu Ram · February 3, 2016
The code is : 

#include <iostream>
using namespace std;

void printarray(int thearray[], int sizeofthearray);

int main()
{
    int Raghu[3] = {1, 2, 5};
    int Ram[4] = {6,7,8,9};

    printarray(Ram, 4);

}

void printarray(int thearray[], int sizeofthearray)
{
    for( int x= 0; x <= sizeofthearray; x++)
    {
        cout<<thearray[x] << endl;
    }

}





And the output of this code is:
6
7
8
9
1


Why did that "1" get displayed when it is not in the array?

Post a Reply

Replies

Oldest  Newest  Rating
0 Laura Lee · February 6, 2016
If you understand how the stack works, you would know that the two arrays are aligned in memory next to each other without any boundaries, when you extend past one array, you will into the memory of the next array. That is the case with "<=" instead of "<".
  • 1

C++

111,317 followers
About

Used in many types of software including music players, video games, and many large scale applications.

Links
Moderators
Bucky Roberts Administrator