編我寫的作品爲一些整數的值,但不是所有...爲什麼?無法正確提取整數字節
程序輸出
int value is abcdef78
first byte is 78 addr is 2686741
second byte is ffffffef addr is 2686742
third byte is ffffffcd addr is 2686743
fourth byte is ffffffab addr is 2686744
預期輸出
int value is abcdef78
first byte is 78 addr is 2686741
second byte is ef addr is 2686742
third byte is cd addr is 2686743
fourth byte is ab addr is 2686744
Process returned 0 (0x0) execution time : 0.015 s
Press any key to continue.
代碼:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int i=0xabcdef78;
int *ip;
printf("int value is %x\n",i); // *ip contents of address
char c;
char *cp;
cp=&i;
c = *cp;
printf("first byte is %x addr is %d\n",*cp++,cp);
printf("second byte is %x addr is %d\n",*cp++,cp);
printf("third byte is %x addr is %d\n",*cp++,cp);
printf("fourth byte is %x addr is %d\n",*cp++,cp);
return 0;
}
更改'%x'→'%hhx'和'%d'→'%p'。另外,如果您希望程序可靠地工作,您應該在printf語句後增加'cp'。 –
該代碼調用*未定義的行爲*。在每個輸出調用中,您都有無法修改和訪問'cp'的情況。 – WhozCraig
也許嘗試使用unit_8t數據類型而不是int。 – LethalProgrammer