C++学习第五课—指针

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值