I have a strange behavior that I can't understand with data in a structure. See my code:
typedef struct _Foo {
char refDossier[12];
char refDossier62 [9];
} Foo;
string refStr = "157809110000";
string ref62Str = "02mFqwTo";
strncpy(fooStruct.refDossier, refStr.c_str(), sizeof (fooStruct.refDossier));
strncpy(fooStruct.refDossier62, ref62Str.c_str(), sizeof (fooStruct.refDossier62));
cout << "REF DOSSIER 62: " << fooStruct.refDossier62 << endl;
cout << "REF DOSSIER: " << fooStruct.refDossier << endl;
Here the result:
REF DOSSIER 62: 02mFqwTo
REF DOSSIER: 15780911000002mFqwTo
I don't understand why the value of fooStruct.refDossier62
appears whyle you print the value of fooStruct.refDossier
.
I know that the data of a structure are contiguous in memory but in my point of view this is not the reason of this strange behavior.
When I run the following code:
for (int i = 0; i< sizeof (fooStruct.refDossier); i++) {
cout << fooStruct.refDossier[i];
}
cout << endl;
for (int j = 0; j< sizeof (fooStruct.refDossier62); j++) {
cout << fooStruct.refDossier62[j];
}
I have a correct output:
157809110000
02mFqwTo
There is therefore no memory overwriting, which I feared.
Any ideas ?