#include <iostream>
#include <math.h>
using namespace std;
int main()
{
long int m,i;
cin>>m;
float first=0,second=0,disp=0;
int arr[m];
char ch[m];
for(i=0;i<m;i++)
{
cin>>arr[i];
}
cout<<" before="<<arr[0]<<endl;
cin>>ch;
cout<<" after="<<arr[0]<<endl;
//puts(ch);
return 0;
}
First i insert elements in an array then Print the zeroth index of an array after that i take string input .Suddenly what happened!. My zeroth index of array got changed!!!. How it's possible ,Would anyone care to explain this
values of the arr[0]
got Changed, why?
The problem is that you input too many characters for
cin >> ch;
. Sincem == 40
, you declared it aschar ch[40]
. This allows you to enter 39 characters (not 40 because of the trailing'\0'
character), but you entered much more than that, so it wrote outside the array boundary, which results in undefined behavior. In this case, it overflowed into thearr
array.I suggest you use
std::string
rather than achar
array, then it will automatically expand to the proper size.