In the following program, I am reading a 6-length string dd and storing its ascii code in an integer array ipc of size 3×2. The problem is that the values stored in ipc are wrong and they change themselves later when I reprint them. I am surprised how can there be such a clear problem with such a simple code. (I am using Code::Blocks 10.05 on Win7 x64)
#include<iostream>
using namespace std;
int main()
{ char dd[5];
int ipc[2][1];
cin.get(dd,6);
for(int i=0;i<3;i++)
{ for(int j=0;j<2;j++)
{ ipc[i][j]=int(dd[j+2*i]);
cout<<ipc[i][j]<<endl;
}
}
cout<<"------"<<endl;
for(int i=0;i<3;i++)
{ for(int j=0;j<2;j++)
{ cout<<ipc[i][j]<<endl; }
}
}
If input given is 123456, the output is:
49
50
51
52
53
2
------
49
51
51
53
53
2
Any sort of help will be very much appreciated. Thank you.
The array declaration is incorrect and the code is going out-of-bounds on the array causing undefined behaviour. Declaration should be changed from:
to:
Additionally,
cin.get()will readcount - 1characters, so:will only read
5characters, not6. If the user enters123456only12345will be read. Thecin.get()will also append a null character, (as commented by tinman). To correct increase the size ofddand the number of characters to be read: