Jerry's Blog

Recording what I learned everyday

View on GitHub


1 January 2021

cpp -- Pointers and Dynamic Memory Management(1)

by Jerry Zhang

Pointer Basics

A pointer variable holds the memory address. Through the pointer, you can use the dereference operator * to access the actual value at a specific memory location.

一般来说,一个变量中存的是一个具体的值,比如一个整数,一个浮点数。而pointer存的是一个变量的内存地址。

声明指针的方法:

dataType* pVarName;

pCount contains the memory address of variable count.

int* pCount = &count;

dereference operator:星号加指针名的意思是:这个指针所指向的值。

(*pCount)++;

指针一定要初始化,否则可能引起严重的程序错误。<iostream>中定义了NULL作为一个常量,它的值是0。

声明指针时,不要这样写:int* p1, p2;。分开单独声明。

Defining Synonymous Types Using the typedef Keyword

如同unsignedunsigned int的同义词,我们可以使用typedef自定义同义词。语法是:

typedef existingType newType;

// 例如:
typedef int integer;

// 然后就可以用以下语句声明一个整数:
integer value = 40;

Using const with Pointers

A constant pointer points to a constant memory location, but the actual value in the memory location can be changed.

tags: cpp