0
点赞
收藏
分享

微信扫一扫

C++中的指针

闲云困兽 2022-01-14 阅读 49


以下为本人大一时阅读《C++ Primer Plus》关于指针的章节所做的笔记
 

指针

一个函数只能返回一个值,但是如果使用指针来传递变量,则可以修改更多的值,可以达到返回不止一个值的效果

用指针作为参数的写法:

void f ( int * nptr){
     *nptr = *nptr * *nptr; //计算平方
}

传递参数时候:

int a;
f ( &a );

sizeof函数的使用:

size_t getsize(int *n){
	return sizeof(n);
}
int main()
{
	int a[20];
	cout<<sizeof(int)<<endl;
	cout<<sizeof a<<endl;
	cout<<sizeof(a)<<endl;
	cout<<getsize(a)<<endl;
	return 0;
}

输出:

​注意:
getsize函数返回的是指针变量所占的大小
对于一个数组a[10],sizeof(a)与sizeof a返回的值相同
但对于普通变量,如int a,使用sizeof函数需写成:

sizeof a;

对于变量类型,写成:

sizeof (int);

指针运算:
指针的运算一般无意义,不过可以用来处理数组
如:

int a[20];
int *p=&a[0];
p+=2;

在这个过程中,p存储的地址的值加上2*4=8
又如:

int a[20];
int *p1=&a[0];
int *p2=&a[2];

则p1-p2=2

 
指针与数组:

int b[10];
int *bptr=b;

则有b[0]=(b)、b[2]=(b+2)
二维数组:
对于a[3][5]
*(*a+1)=a[0][1]
*(*(a+1)+1)=a[1][1]

 

new和delete

Free store:
有时候也称为heap
分配给每个程序用于存储在执行时创建的对象的内存区域

new操作:
申请内存(allocates (i.e., reserves) storage of the proper size for an object at execution time)
调用构造函数来初始化对象(calls a constructor to initialize the object)
返回指定到new右边的类型的指针(returns a pointer of the type specified to the right of new )

delete操作:
删除对象(destroys a dynamically allocated object)
调用对象的析构函数(calls the destructor for the object)
释放内存(deallocate memory from the free store)

用法演示:

int *p1=new int;
char *p2=new char;
int *p3=new int[4];//数组
delete p1;
delete p2;
delete []p3; //删除数组

初始化由new分配的对象

double *ptr = new double( 3.14159 );
cout<<*ptr;

注意:
int *p=new int[10];
申请了一个含有与10个元素的int型数组
这时是同时申请了10个int的内存空间
可以使用p[i]来表示这个数组中的某个元素
delete []p;
是同时将这个数组的所有元素删除

delete p;
只有将这个数组的第一个元素删除

举报

相关推荐

C++中的this指针

c++中的指针

c++ 中的函数指针

c++中的函数指针

C++中的智能指针

C++中的const与指针

C++的this指针

0 条评论