xan99
xan99

Reputation: 3

Array values changing by themselves in C++

In the following program, I am reading a 6-length string dd and storing its ascii code in an integer array ipc of size 3x2. 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.

Upvotes: 0

Views: 1804

Answers (1)

hmjd
hmjd

Reputation: 121961

The array declaration is incorrect and the code is going out-of-bounds on the array causing undefined behaviour. Declaration should be changed from:

int ipc[2][1]; 

to:

int ipc[3][2];

Additionally, cin.get() will read count - 1 characters, so:

cin.get(dd, 6);

will only read 5 characters, not 6. If the user enters 123456 only 12345 will be read. The cin.get() will also append a null character, (as commented by tinman). To correct increase the size of dd and the number of characters to be read:

char buf[7];
cin.get(buf, 7);

Upvotes: 12

Related Questions