C++ - 指针总结

指针是什么?

指针是一变量或函数的内存地址,是一个无符号整数,它是以系统寻址范围为取值范围,32位,4字节。

 

指针变量:

存放地址的变量。在C++中,指针变量只有有了明确的指向才有意义。

 

指针类型

int*ptr; // 指向int类型的指针变量
char*ptr;
float*ptr;

 

指针的指针:

char*a[]={"hello","the","world"};
char**p=a;
p++;
cout<<*p<<endl; // 输出the

 

函数指针:

指向某一函数的指针,可以通过调用该指针来调用函数。

例子:

#include <stdio.h>
#include <io.h>
#include <stdlib.h>
#include <iostream>

using namespace std;

int max(int a, int b)
{
	return a>b?a:b;
}

int main(int argc, char* argv[])
{
	int a=2,b=6,c=3;
	int max(int, int);
	int (*f)(int, int)=&max;
	cout<<(*f)((*f)(a,b),c);
	return 0;
}

// Output:
/*
6
*/

 

指针数组:

指向某一种类型的一组指针(每个数组变量里面存放的是地址)
int* ptr[10];

 

数组指针:

指向某一类型数组的一个指针
int v[2][10]={{1,2,3,4,5,6,7,8,9,10},{11,12,13,14,15,16,17,18,19,20}};
int (*a)[10]=v; // 数组指针
cout<<**a<<endl; // 输出1
cout<<**(a+1)<<endl; // 输出11
cout<<*(*a+1)<<endl; // 输出2
cout<<*(a[0]+1)<<endl; // 输出2
cout<<*(a[1]+1)<<endl; // 输出12
cout<<a[0]<<endl; // 输出v[0]首地址
cout<<a[1]<<endl; // 输出v[1]首地址

 

int* p与(int*) p的区别

int* p; // p是指向整形的指针变量
(int*) p; // 将p类型强制转换为指向整形的指针

 

数组名相当于指针,&数组名相当于双指针

 

char* str="helloworld"与char str[]="helloworld"的区别

char* str="helloworld"; // 分配全局数组,共享存储区
char str[]="helloworld"; // 分配局部数组

再分享一下我老师大神的人工智能教程吧。零基础!通俗易懂!风趣幽默!希望你也加入到我们人工智能的队伍中来!http://www.captainbed.net

猜你喜欢

转载自www.cnblogs.com/kwincaq/p/10109836.html