当前位置:网站首页>Chapter 4-2 a complex type (pointer)

Chapter 4-2 a complex type (pointer)

2022-08-11 05:45:00 Zinxso

第4章

4.7 指针和自由存储空间

Computers must keep track of when they store data3种基本属性:
 信息存储在何处
 存储的值为多少
 存储的信息类型
指针是一个变量,其存储的是值的地址,而非值本身.
Pass the address operator on a regular variable(取址运算符)&to get its location,例如home变量,&homeis its address;*运算符被称为间接值或解除引用运算符,Use the pointer to get the value stored at this address,例如manly指针,*manly即是manlyThe value stored at the address.

4.7.1 声明和初始化指针

int *ptr;    //CGet used to this,强调*ptr是一个int类型的值
int* ptr;    //C++Get used to this,强调int*是一种类型——指向int的指针
int*ptr;     //valid,三种方式都可以
int* p1, p2;  //创建了一个指针p1,一个int变量p2 

One pointer variable name corresponds to one*.
The data types pointed to by different types of pointers have different lengths,But the two pointer variables themselves are usually the same length.比如:double* p1,int* p2,p1和p2It takes up the same memory space itself.

4.7.2 指针的危险

C++中创建指针时,计算机将分配用来存储地址的内存,但不会分配用来存储指针所指向的数据的内存.

long * fellow;           //No address was assigned tofellow
* fellow = 22333;        //22333不知道放在哪里

The above code is dangerous,Can lead to some of the most stealthy and hard to trackBUG.
warning:一定要在对指针解除引用运算符(*)之前,Initialize the pointer to a determined appropriate address,This is the golden rule for using pointers.

4.7.3 指针和数字

指针为地址,非整型(Timely addresses are usually treated as integers),不能简单地将整数赋给指针.

int* pt;
pt = 0xB80000000;      //type mismatch

//通过强制类型转换:
int* pt;
pt = (int*)0xB80000000;  //type now match

4.7.4 使用new分配内存

The above all initialize the pointer to the address of the variable.That's where pointers really come in——在运行阶段分配未命名的内存以存储值.这种情况下,只能通过指针来访问内存.
语法格式:

typeName * pointer_name = new typeName;

需要在两个地方指定数据类型:用来指定需要什么样的内存和用来声明合适的指针.
例如:

int * pt = new int;

new运算符根据类型来确定需要多少字节的内存,Then return its address to assignpn,pn是被声明为指向int的指针.pn是地址,*pnThe value stored for this address.

4.7.5 使用delete释放内存

为避免内存泄露(memory leak),delete和new配对使用.
例如:

int * pt = new int;delete pt;      //并不会删除pt值,只会删除pt指向的内存空间

delete会释放pt指向的内存,并不会删除pt值,只会删除pt指向的内存空间.此时,还可将pt重新指向另一个新分配的内存块.
warning:
 不要尝试释放已经释放的内存块
 不能用delete来释放声明变量所获得的内存(只适用于new)

int jugs = 5;
int* pi = &jugs;
delete pi;       //not allowed, memory not allocated by new

Like the house itself is not your own,Unable to sell;But if the house isnew来的,自己创建的,买来的,才可以delete.
 不要创建两个指向同一个内存块的指针

4.7.6 使用new创建动态数组

对于大型数据应使用new正是new的用武之地.
静态联编:Arrays are allocated memory at compile time.This means that arrays are added to the program at compile time.
使用newArrays can be created on demand at runtime,Not created if not needed,还可以在运行时选择数组的长度,此为动态联编.这意味着数组是在程序运行时创建的.这种数组称为动态数组.
When using static binding, the array length must be specified when writing the program;Using dynamic binding will determine the array length at runtime.

  1. 使用new创建动态数组
int * psome = new int [10];    //get a block of 10 int

newThe operator returns the address of the first element assigned to the pointerpsome.
delete释放指针:

delete [] psome

使用new时,不带[]则使用deletetime does not bring[];反之,should also be brought.
使用new和delete遵守规则:
 不要使用delete释放不是new分配的内存
 不要使用delete释放同一个内存两次
 如果使用new[]为数组分配内存,则应使用delete[]释放
 如果使用new为一个实体分配内存,则使用delete(无[])来释放
 对空指针应用deletetime safe
2. 使用动态数组
指针和数组基本等价.Array elements can be accessed by index subscripting.

double* pt = new double [3];
pt[0] = 0.2;
pt[1] = 0.5;
pt[2] = 0.8;

double a = pt[1];
pt = pt + 1;
double b = pt[0];

delete [] pt;

此时,a = b.
相邻的int地址通常相差2或4个字节,而将pt+1后,它将指向下一个元素的地址,This suggests that there is something special about pointer arithmetic.

4.8 指针、数组和指针算术

指针和数组基本等价,Pointers and array names can be used in the same way,可以使用数组方括号表示法,也可以使用解除引用运算符(*).
算术,将整数变量加1,其值将增加1;指针变量加1,增加的量等于它指向的类型的字节数,That is, the next address of the current address.
指针和数组的区别:
 指针的值可以修改,而数组名是常量.

pointname = pointname + 1;   //valid
arrayname = arrayname + 1;   //not allowed

 sizeof运算符,Array application returns the length of the array,Pointer application returns is the length of the pointer.
数组的地址:数组名被解释为其第一个元素的地址,而对数组名应用地址运算符时,The return is the address of the entire array.

4.8.2 指针小结

  1. 声明指针
typeName * pointerName;
  1. 给指针赋值
    应将内存地址赋给指针,Can be applied to variable names&operator to get the address of the named memory ornew运算符返回未命名的内存的地址.
  2. 对指针解除引用
    That is, get the value pointed to by the pointer,一种方式是通过()来解除引用,Another is to use array notation[].比如pn[0]和pn是一样的.
    注意:Never dereference a pointer that is not initialized to an appropriate address
  3. Distinguish between pointers and what the pointers point to
    如果pt是指向int的指针,*pt不是指向int的指针,but an exact equivalent of int类型的变量.

4.8.3 指针和字符串

C风格字符串:

char flower[10] = “rose”;
cout << flower << “s are red\n”; 

数组名是第一个元素的地址,因此cout中的flower是包含字符r的char元素的地址.cout对象认为char的地址是字符串的地址,because it prints the character at that address,Then continue printing until a null character is encountered{\n}为止;而cout中的“s are red\n”Also the same as the array name,Also passed is the address of the first element,Print the characters at the address,Then continue printing until a null character is encountered{\n}为止.
总而言之,如果给cout提供一个字符的地址,It will print from that character until a null character is encountered.

4.8.4 使用new创建动态结构

可以使用newThe operator allocates the required space for the structure when the program runs.
例如,创建一个未命名的inflatable类型,并将其地址赋给一个指针:

inflatable * ps = new inflatable;   //will be enough to storeinflatable结构的一块可用内存地址赋给ps

Access structure member methods:

  1. 创建动态结构,不能将成员运算符(.)用于结构名,Instead is the arrow member operator(->)来访问结构体成员,如上述ps->price,that is structuralprice成员.
  2. *ps就是结构本身,也就是inflatable,则可以使用(*ps).price访问结构体的price成员.
    Used when a function returns a large temporary arraynew[]Create a block of memory just large enough to store its contents,并返回一个指向该内存块的指针,可以节省大量内存( ).

4.8.5 自动存储、静态存储和动态存储

根据用于分配内存的方法,C++的3种管理数据内存的方式.

  1. 自动存储
    函数内部定义的常规变量使用自动存储空间,称为自动变量,常见temp,exists in a block of code{}里的变量.Let's just say local variables.
  2. 静态存储
    A storage method that exists for the entire duration of the program,全局变量.
  3. 动态存储
    More flexible than both of the above.new和deleteMakes it possible to allocate memory within a function,而在另一个函数中释放它.Be sure to use bothnew和delete.

4.9 类型组合

Arrays can be combined in various ways、结构和指针.

4.10 surrogate for data

4.10.1 模板类 vector

vector类似string类,动态数组,Can be set during runtimevector对象的长度,New data can also be appended at the end or inserted in the middle.
使用须知:
 首先,必须包含头文件vector
 Vector包含在名称空间std中,可使用using编译指令,using声明或std::vector
 Templates use a different syntax to indicate the type of data they store
 Vector类使用不同的语法来指定元素数
声明模板:

vector<typeName> vt(n_elem);

创建一个命为vt的vector对象,可存储n_elem个typeName的元素,n_elemIt can be either an integer constant or an integer variable.
例如:

# include <vector>using namespace std;
vector<int> vi;       // create z zero-size array of int
int n = 3;
vector<double> vd(n);    //create an array of n doubles

4.10.2 模板类array(C++11)

vectorClasses are more powerful than arrays,But the efficiency is slightly lower,Applies to fixed-length arrays,The price is less convenience and safety.
鉴于此,C++11Added template classarray,Also in the namespacestd中.
arrayThe length of the object is fixed,Applicable stack(静态内存分配),instead of free storage,因此效率与数组相同,But more convenient and safe.
Header files must also be included when usingarray.
声明模板:

array<typeName, n_elem> arr;

创建一个命为arr的array对象,包含n_elem个typeName类型的元素,n_elem不能是变量.
例如:

# include<array>
…
Using namespace std;
array<int, 5> a;
array<double, 4> b = {
    1.2, 1.3, 1.4, 1.5};

4.10.3 数组、vector对象和array对象的区别

共同点
Both can use standard array notation(数组下标索引)访问各个元素.
不同点
array对象和数组存储在相同的内存区域(栈)中,vectorObjects are stored in free storage or the heap;
arrayObjects can be directly assigned to anotherarray对象,Arrays must be copied element by element.

原网站

版权声明
本文为[Zinxso]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/223/202208110512453106.html