关于指针的有趣问题..请帮助

发布于 2024-09-18 10:03:54 字数 863 浏览 2 评论 0原文

#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;
}           

Sixeof(ptr) 和 Sizeof(a) 显示 4
sizeof(int) 显示 4,sizeof(char) 显示 1
所以 65 存储在 4 个字节中,即
00000000 00000000 00000000 01000001 并且第一个字节的地址存储在 ptr 中

在上面的代码中,我将 int* 类型转换为 char* ,目的是打印 x(type 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

PS - 我正在开发 Dev-C++

#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;
}           

Sixeof(ptr) and Sizeof(a) display 4
Sizeof(int) displays 4 and sizeof(char) displays 1
So 65 is stored in 4 bytes ie
00000000 00000000 00000000 01000001 and address of first bytes is stored in ptr

In the above code I have type casted the int* to char* in a motive to print the value stored in x(type int) first byte.

So after typecasting "a" stores the first byte address ie contained in ptr as well
Now on displaying (int)*a shouldn it consider only first byte for showing the value..??
but the output is 65 instead of 0(first byte value)..Where am I going wrong..?

what I have learnt is

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

PS - I am working on Dev-C++

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

神仙妹妹 2024-09-25 10:03:54

你的机器是little-endian,最低有效字节在前。

Your machine is little-endian, and least significant bytes go first.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文