Assigning an integer to a dereferenced character pointer

Viewed 51
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?

1 Answers

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;.

Related