在订阅的某邮件列表里看见这样一个问题:
Hi, having coding in C for 3 years but I'm still not clear with this one.
Consider this code.
...
char *p;
unsigned int i = 0xcccccccc;
unsigned int j;
p = (char *) &i;
printf("%.2x %.2x %.2x %.2x\n", *p, p[1], p[2], p[3]);
memcpy(&j, p, sizeof(unsigned int));
printf("%x\n", j);
...
Output:
ffffffcc ffffffcc ffffffcc ffffffcc
0xcccccccc
My questions are:
1. Why it prints "ffffffcc ffffffcc ffffffcc ffffffcc"? (if p is
unsigned char* then it will print correctly "cc cc cc cc")
2. Why pointer to char p copied to j correctly, why not every memberin p overflow? since it is a signed char.
问题2我想不用多说了,我觉着没什么问题。
问题1是个不常用的printf特性,自己实验了一下。
#include <stdlib.h>
#include <stdio.h>
int main(void)
{
char a = 0xcc;
unsigned char b = 0xcc;
printf("%.2x\n", a);
printf("%.2x\n", b);
char *p = &a;
unsigned char *q = &a;
printf("%.2x\n", *p);
printf("%.2x\n", *q);
p = &b;
q = &b;
printf("%.2x\n", *p);
printf("%.2x\n", *q);
exit(0);
}
结果如下:
gcc printf.c && ./a.out
ffffff8c
cc
ffffff8c
8c
ffffffcc
cc
发现结论如下:
当以%.2x格式打印