实例1 探索局部变量在内存中的存放方式
#include<iostream>
using namespace std;
struct student{
int num;
int dum;
};
int main()
{
student a ;
int b;
int c;
int d;
int e[10];
cout<<&(a.dum)<<endl;
cout<<&(a.num)<<endl;
cout<<"a="<<&a<<endl;
cout<<"b="<<&b<<endl<<"c="<<&c<<endl;
cout<<"d="<<&d<<endl;
cout<<"e="<<&e<<endl;
((struct student *)&a.dum)->num=12;
((struct student *)&a.dum)->dum=22;
cout<<d<<endl;
cout<<((struct student *)&a.dum)[0].dum<<endl;
return 0;
}
程序输出为:
0xbfbf6410
0xbfbf640c
a=0xbfbf640c
b=0xbfbf641c
c=0xbfbf6418
d=0xbfbf6414
e=0xbfbf63e4
22
22
按照之前的理解栈地址向下增长,即小地址方向增长。
分析 | 实际(ubuntu) |
a | b |
b | c |
c | e |
d | a |
e | e |
实例2 通过对变量的存储模式的了解,通过void* 型来实现C语言的泛型。
#include <stdio.h>
#include <stdlib.h>
void swap(void* vp1,void* vp2 ,int size)
{
char *buf=malloc(sizeof(char)*size);
memcpy(buf,vp1,size);
memcpy(vp1,vp2,size);
memcpy(vp2,buf,size);
free(buf);
}
int main()
{
int a=1,b=2;
double x=1.1,y=2.2;
char *str1=strdup("jackkk");
char *str2=strdup("luse");
swap(&a,&b,sizeof(int));
swap(&x,&y,sizeof(double));
swap(&str1,&str2,sizeof(char *));
printf("a=%d,b=%d\n",a,b);
printf("x=%f,y=%f\n",x,y);
printf("str1=%s,str2=%s\n",str1,str2);
return 0;
}
a=2,b=1 x=2.200000,y=1.100000 str1=luse,str2=jackkk 对于str1和str2时间上是交换来str1和str2的指向,即memcpy实际上是copy其指向的地址。如果调用swap(str1,str2,sizeof(char *))将只交互指向内存的四个字节内容。不能实际完成要求。