#include<iostream>
#include<conio.h>
using namespace std;
int main()
{
int x = 65;
int *ptr = &x;
char * a= (char *)ptr;
cout<<(int)*(a);
getch();return 0;
}
Run Code Online (Sandbox Code Playgroud)
Sixeof(ptr)和Sizeof(a)显示4
Sizeof(int)显示4和sizeof(char)显示1
所以65存储在4个字节中,即
00000000 00000000 00000000 01000001,第一个字节的地址存储在ptr中
在上面的代码中,我有一个类型将int*转换为char*,以打印存储在x(int)第一个字节中的值.
因此,在类型转换后,"a"存储第一个字节地址,即包含在ptr中,现在在显示(int)*a时,它应该只考虑显示值的第一个字节.但输出是65而不是0(第一个字节值)..我哪里错了..?
我学到的是
char * ptr1;
ptr1++; //Ptr1 goes to the next byte..*ptr1 will display only 1 byte value
int * ptr2;
ptr1++; //Ptr2 goes to the next 4 byte..*ptr2 will display value conmtain in 4 bytes
Run Code Online (Sandbox Code Playgroud)
PS - 我正在研究Dev-C++
rkh*_*rov 13
你的机器是little-endian,最不重要的字节是第一位的.