I have to enter values ayba unsigned char variables but I don't quite understand the unsigned well, my code is this:
#include<stdio.h>
#include<iostream>
#include <sstream>
#include <string.h>
using namespace std;
int main(){
unsigned char a[5],b[4];
cout<<"Ingresa A: "; cin>>a;
cout<<"Ingresa B: "; cin>>b;
cout<<"A:"<<a<<endl;
cout<<"B:"<<b<<endl;
return 0;
}
and the error it gives me is the following
I enter a and b but a doesn't print it, and if I check 1 for example it exists but a[0] doesn't I don't know what else to do :c
There is no overload of the read-from-stream operator (
>>
) that accepts character formations:So the read decays to the version of the operator that reads over a pointer.
When we read from the console (
c
onsolein
put ) and pass a pointer, it will read to the end of the line, so with this input:In the data buffer we have:
'1'
'0'
'1'
'0'
'\n'
'1'
'0'
'1'
'0'
'\n'
Five bytes are read (from the first character to the line break) on the first variable and then another five on the second variable, since the data on which it is read has decayed to a pointer, the size information is lost and no data is made. limit checks, nothing would happen except for the detail that one of the variables does not have five elements but four:
Writing to elements outside of an array is undefined behavior, so anything could have happened, but what I think happened in this case is the following:
The arrays
a
andb
are in memory distributed in the reverse order of the definition:b[0]
b[1]
b[2]
b[3]
a[0]
a[1]
a[2]
a[3]
a[4]
When reading about the formation
a
everything works correctly:b[0]
b[1]
b[2]
b[3]
a[0]
a[1]
a[2]
a[3]
a[4]
'1'
'0'
'1'
'0'
0
The null character (
0
) is stored in the last position, indicating the end of the string.Reading over the formation
b
overwrites the first character of the formationa
:b[0]
b[1]
b[2]
b[3]
a[0]
a[1]
a[2]
a[3]
a[4]
'1'
'0'
'1'
'0'
0
superscript!'0'
'1'
'0'
0
The null character (
0
) is stored in the last position, indicating the end of the string.When printing, since the formation
a
begins with the null character (0
), the string is considered to be empty.We can check that this is what happens if we print the content as a number:
The code above shows:
Another proof of this is that by changing the definition order (
unsigned char b[4],a[5];
) the problem does not occur; it also doesn't happen if both arrays are large enough to hold all the characters (unsigned char a[5],b[5];
).