Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
275 views
in Technique[技术] by (71.8m points)

c - Assigning an integer to a dereferenced character pointer

int main(){
 char a = 5;
 char *p = &a;        // 8 bits
 int num = 123456789; // 32 bits
 *p = num;
 return 0;
}

As a is 1 byte and num is 4 bytes, does *p = num truncate num to 1 byte before assigning it to a? or a 32 bit value gets written to memory and corrupts the stack?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Since you're assigning an int value to a char, the value is converted in an implementation-defined way to be in the range of a char (most likely, the low order byte of num will be the value which is assigned).

The fact that you're dereferencing a char * to assign to a char doesn't change this. It would be the same as if you did a = num;.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...