reinterpret_cast问题 [英] reinterpret_cast question
问题描述
你能帮忙检查一下为什么代码没有正确打印变量charPtr1和charPtr2吗?
Could you help to check why the code didn't print the variable charPtr1 and charPtr2 correctly?
这是我的代码,谢谢
结果是:
地址= 00000032D70FFDA8; a = 100
地址= 00000032D70FFDAC; b = 101
地址= cd; c = c
地址 =; d =
address=00000032D70FFDA8;a=100
address=00000032D70FFDAC;b=101
address=cd;c=c
address=;d=
#include <iostream>
using namespace std;
struct sample
{
public:
int a;
int b;
char c;
char d;
};
void main(void)
{
sample s1;
s1.a=100;
s1.b=101;
s1.c='c';
s1.d='d';
sample *s=&s1;
int *intPtr1=reinterpret_cast<int*>(s);
cout<<"address="<<intPtr1<<";a="<<*intPtr1<<endl;
intPtr1++;
int *intPtr2=reinterpret_cast<int*>(intPtr1);
cout<<"address="<<intPtr2<<";b="<<*intPtr2<<endl;
intPtr1++;
char *charPtr1=reinterpret_cast<char*>(intPtr1);
cout<<"address="<<charPtr1<<";c="<<*charPtr1<<endl;
intPtr1++;
char *charPtr2=reinterpret_cast<char*>(intPtr1);
cout<<"address="<<charPtr2<<";d="<<*charPtr2<<endl;
}
推荐答案
On 3 / 26/2017 7:25 PM,cppBeginnnnnner写道:
On 3/26/2017 7:25 PM, cppBeginnnnnner wrote:
你能帮忙检查一下为什么代码没有正确打印变量charPtr1和charPtr2吗? />
&NBSP; char * charPtr1 = reinterpret_cast< char *>(intPtr1); &NBSP; &NBSP; cout<<<" address ="<< charPtr1<<" ;; c ="<< * charPtr1<< endl;
Could you help to check why the code didn't print the variable charPtr1 and charPtr2 correctly?
char *charPtr1=reinterpret_cast<char*>(intPtr1); cout<<"address="<<charPtr1<<";c="<<*charPtr1<<endl;
运算符<<(char *)的重载,假设指针指向NUL终止的字符串,并打印该字符串。如果要打印地址,请将指针转换为void * first:
There's an overload of operator<<(char*), which assumes the pointer points to a NUL-terminated string, and prints that string. If you want to print the address, cast the pointer to void* first:
cout<<"address="<<(void*)charPtr1;
这篇关于reinterpret_cast问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!