简体   繁体   中英

Why a char variable overlaps the char array after it in the input console when it 's casted to ((char*)&)? in c++ codeblocks

When i cast a char var. using this operator "&"( i really have to cast it to write it in a char [] to write it in a file as a fixed length record ) the casted value is the char concatenated to the char [] which i wrote in the input console after it . (if the next attribute was not char [] no thing happens and it does not overlaps only if it is a char [] it overlaps) . Because of that prob. i can not maintain that records are written correctly . Anyone know why this prob. happens? Thanks in advance .

I have tried to search and found that casting char to ((char*)&) is not safe . but i still can not understand how casting process used the char [] attribute after it in the console of input

The code that refers to the problem:

struct citizen
{

    char gender ;

    char name [10] ;

};

istream& operator>>(istream& in, citizen& c)

{  
     in >>c.gender ; // input f 

     in>>c.name ; // iput mariam 

     cout<<c.gender ; // outputs "f"

     cout<<(char*)&c.gender; // outputs " fmariam"

     return in ;

}

The << operator for cout depends on the type of its argument. c.gender is a type char , so cout outputs its character value. &c.gender is the address of a char... analogous to a char * (so your cast doesn't do anything). As a char * , cout<< interprets the reference as an array of characters, terminated with a '\\0' character, aka a "nul terminated string." Since the fields of the struct are packed, cout doesn't see a '\\0' until the end of the array of characters adjacent to the gender field.

You're kinda lucky your program didn't crash.

The stream insertion operator requires that a char* inserted into the stream points to an array of characters terminated by the null-character.

char gender is not a null-teminated array of characters (unless the value happens to be the null-terminator, in which case it can be treated as an array of one characters representing an empty string as far as pointer arithmetic is concerned).

By inserting the non-null-terminated char* into the stream, you violate the requirement mentioned above, and as a result, the behaviour of your program is undefined.

why this prob. happens?

Because the behaviour of your program is undefined.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM