#include<iostream>
#include<string>
using namespace std;
struct MyStruct
{
int name = 1;
char a = 'n';
string b = "hello world";
}mystruct;
int main() {
/*int a = 1000;
void* ptr = &a;
int* ptr2 = (int*)ptr;
cout << *ptr2 << endl;*/
MyStruct* M = &mystruct;
cout << *(char*)((int*)M + 1) << endl;
cout << *(char*)((char*)M + 4) << endl;
return 0;
}
下面的代码虽然没有任何实际意义,但有助于剖析指针。如果想用指针取结构体中字符a,cout << *(char*)((int*)M + 1) << endl;cout << *(char*)((char*)M + 4) << endl;两行具有同样的效果,结构体中包含int char string 三种类型;指针M代表结构体的起始地址,将m强转int*,只要+1就跨过name,再强转char*,解引用就可以拿到char a的值。同样的道理强转char*就需要加4个字节的偏移量。
#include<iostream>
#include<string>
using namespace std;
struct MyStruct
{
int name = 1;
char a = 'n';
string b = "hello world";
}mystruct;
int main() {
/*int a = 1000;
void* ptr = &a;
int* ptr2 = (int*)ptr;
cout << *ptr2 << endl;*/
MyStruct* M = &mystruct;
cout << *(string*)((int*)M + 2) << endl;
cout << *(string*)((char*)M + 8) << endl;
return 0;
}
如果想拿到helloworld呢?同样的方法,(int型与char型字节对齐,所要跨过8个字节)最后将其转化为string*型的地址存储空间。