您的位置:首页 > 编程语言 > C语言/C++

C++学习第五课—指针

2015-11-16 15:03 423 查看
C++ pointers

指针的定义:type * name

int *p1;
char *p2;

指针的数值就是变量的地址,是十六制的,指针类型的不同只在于指针所指向的变量类型不同,只会影响p++,p--

空指针:

#include <iostream>
using namespace std;
int main()
{
int *p=NULL;
cout << p;//最终显示结果为0,没有指向任何值
return 0;
}

空指针的值为0,为了防止指针为空指针,可以前期对指针进行判断

if(p) // succeeds if p is not NULL
if(!p)// succeeds if p is NULL


指针的指针:

int p;
int *ptr;
int **pptr;
ptr=&p;
pptr=&ptr;


指针的数组:

int *ptr[4];

下列是一组字符串,有点类似数组定义

char a[ ]="Hello";

char *a="Hello"

cout << a;// 结果均为为Hello,但第一行与第二行的区别在于,数组地址不可改变,但指针可以改变

#include <iostream>

using namespace std;
const int MAX = 4;

int main ()
{
char *names[MAX] = {
"Zara Ali",
"Hina Ali",
"Nuha Ali",
"Sara Ali",
};

for (int i = 0; i < MAX; i++)
{
cout << "Value of names[" << i << "] = ";
cout << names[i] << endl;
}
return 0;
}
Value of names[0] = Zara Ali
Value of names[1] = Hina Ali
Value of names[2] = Nuha Ali
Value of names[3] = Sara Ali


指针的传递和返回:

传递:

#include <iostream>
#include <ctime>

using namespace std;
void getSeconds(unsigned long *par);

int main ()
{
unsigned long sec;
getSeconds( &sec );

// print the actual value
cout << "Number of seconds :" << sec << endl;

return 0;
}

void getSeconds(unsigned long *par)
{
// get the current number of seconds
*par = time( NULL );
return;
}


返回:

int *myFunction()

{...

 ...

}

注意:若是要返回一个局部变量的地址,需要在变量前面加上static
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  C++ 基础学习