数组指针的实验
#include<iostream> #include <cstring> using namespace std; int main() { int arr[10]; int * parr=arr; for (int i = 0; i < 10; i++) { arr[i]=i; } cout<<"arr = "<<arr<<endl; cout<<"arr + 1 = " << arr + 1 <<endl; //比arr加了4,也就是sizeof int cout<<"&arr = "<<&arr<<endl; //和arr的值相等 cout<<"&arr + 1 = "<<&arr + 1<<endl; //加了整个数组的 size ! cout<<"*arr = "<< *arr<<endl; //是arr数组第一个值 cout<<"*(arr + 1) = "<< *(arr + 1)<<endl; //是arr数组第二个值 cout<<"sizeof(arr) = "<<sizeof(arr)<<endl; cout<<"--------------------- "; cout<<"parr = "<<parr<<endl; cout<<"parr + 1 = "<<parr+1<<endl; //也是加了4 cout<<"&parr = "<<&parr<<endl; //和parr的值不相等 是指针的地址 ! cout<<"&parr + 1 = "<<&parr+1<<endl; //加了8,是一个地址的size cout<<"sizeof(parr) = "<<sizeof(parr)<<endl; cout<<"*parr = "<<*parr<<endl; parr = new int[10]; // for (int i = 0; i < 10; i++) // { // parr[i]=i; // } cout<<"----------Before memset----------- "; cout<<"arr values: "; for (int i = 0; i < 10; i++) { cout<<arr[i]<<' '; //如果之前不初始化也可以成功访问但也是乱码 } cout<<endl; cout<<"parr values: "; for (int i = 0; i < 10; i++) { cout<<parr[i]<<' '; //成功访问但是是乱码 } cout<<endl; //vs编译器的结果他们乱码的值好像都是10个一样的值,但是gcc编译出来的只有parr的乱码是10个一样的,arr的则是不规则数字,0为多数 cout<<"----------After memset----------- "; memset(arr,0,sizeof(arr)); memset(parr,0,sizeof(int)*10); for (int i = 0; i < 10; i++) { cout<<arr[i]<<' '; //全0 } cout<<endl; for (int i = 0; i < 10; i++) { cout<<parr[i]<<' '; //也是全0,成功 } cout<<endl; cout<<"----------After memset 9----------- "; memset(arr,9,sizeof(arr)); memset(parr,9,sizeof(int)*10); for (int i = 0; i < 10; i++) { cout<<arr[i]<<' '; } cout<<endl; for (int i = 0; i < 10; i++) { cout<<parr[i]<<' '; } cout<<endl; //都乱码,但其实 9 = 0000 1001 //又因为int值是4个字节所以 赋值为 0000 1001 0000 1001 0000 1001 0000 1001 的出来就是 151587081 }
可以随便找个二进制转换网站验证
上方实验输出结果:
memset作用
本质上就是,将内存空间的首n个字节的值设为某个确认的值,如果要保证赋值准确,赋值0或者赋值给大小为1字节的变量
例如:
#include<iostream> #include <cstring> using namespace std; typedef class Person { public: char name; Person(){}; Person(char name_):name(name_){}; void introduce() { cout<<"Hello my name is "<<name<<endl; } } *pp ; int main() { pp p; p=new Person('a'); cout<<"size of "<<p->name<<" is "<<sizeof(Person)<<endl; p->introduce(); cout<<"name changed "; memset(p,'c',sizeof(Person)); p->introduce(); }
输出结果: