关于指针的一些概念,作用

Pointers

A pointer holds the memory address of an object. For a type T, T* is the type "pointer to T". For example,

int i = 5;
int* ptr_to_i = &i; // ptr_to_i holds the address of i
int *also_ptr_to_i = ptr_to_i;

The type of ptr_to_i is int*. Prefix unary & is the "address of" operator.

It is preferable to write

int *p;

rather than

int* p;

This is because in the following example:

int* p1, p2; // whoops, p2 is not a pointer-to-int

p1 is a pointer-to-int while p2 is a plain int. To make both variables pointers, we write this:

int *p1, *p2; // p1 and p2 are pointer-to-int

Dereferencing

The fundamental operation on a pointer is dereferencing. When you dereference a pointer, you get the object that the pointer is "pointing to". The dereferencing operator is prefix unary *. For example:

char c = 'w';        // c has the value 'w'
char *ptr_to_c = &c; // ptr_to_c holds the address of c 
char c2 = *ptr_to_c; // dereference---c2 has the value 'w'

By dereferencing a pointer, we can change the value of the object pointed to:

char c = 'x';
char *ptr_to_c = &c;
*ptr_to_c = 'y'; // c now has the value 'y'

Null Pointer

A pointer with the value zero (0) is a pointer that points to nothing. You must check that a pointer is not a NULL pointer before using it. Consider a function that takes a pointer as an argument:

void someFunction(int *p)
{
  if( p ) {
    // p is not NULL---ok to use it here
  }
  else {
    // p is NULL---don't use p as is
  }
}

Pointers and const

You should read pointer declarations from right to left. For example:

int *p; p is a pointer to an int.

const int *p; p is a pointer to a const int. The const int object cannot be changed via the pointer.

int *const p; p is a const pointer to an int. The int object can be changed by the pointer, but the pointer itself cannot be changed.

const int *const p; p is a const pointer to a const int. The const int object cannot be changed by the pointer, and the pointer itself cannot be changed.

The following example is from Stroustrup:

void f1(char *p)
{
  char s[] = "Gorm";

  const char *pc = s;        // pointer to constant
  pc[3] = 'g';               // error: pc points to constant
  pc = p;                    // ok

  char *const cp = s;        // constant pointer
  cp[3] = 'a';               // ok
  cp = p;                    // error: cp is constant

  const char *const cpc = s; // const pointer to const
  cpc[3] = 'a';              // error: cpc points to constant
  cpc = p;                   // error: cpc is constant
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值