Usage of C++new (involving pointers)

First of all, new and delete are used in pairs. new is used to apply for a piece of space from the heap memory . Generally, dynamic is used to dynamically apply for memory space, that is, to apply for a certain length of space according to the needs of the program, and delete is to apply for the new space. freed.

The space opened up by new is on the heap, while the generally declared variables are stored on the stack.

1. Three basic formats for new application memory space

  • new data type

  • new data type (initial value)

like

  int  * p1=new int;

  int  *p2=new int(2); // *p2初始化值是2,这样直接在定义后面初始化是可以的
//也可以单独赋值  *p2=2;

 //如果不想使用指针,可以定义一个变量,在new之前用“*”表示new出来的内容
  int q = *new int;
  q = 1;
  cout << q << endl;

  int  *p3=new int[1000] //申请1000个单位内存空间

Because system resources are limited.

Therefore, after the application is completed, a condition is generally added for judgment (it is not required in general cases, but it is required when applying for a particularly large memory)

void Test()

{
 if(p3!=null)

{

   //程序代码
}

else

{

  //抛出异常,内存空间申请失败
}
 
}

Remember to delete after use

Note: You can only delete once, do not use delete for the same pointer multiple times

 delete p0;  //错误的,p0指针不是用new动态申请的
//下面三个是正确的写法

 delete p1;

 delete p2;

 delete[] p3; //注意此处不能用delete p3,因为在申请用了[],则在释放时要用delete[]
//注意   []中什么也不写

}

2. Use new to create dynamic arrays

like

int main()
{
using namespace std;
double* p3=new double[3];
p3[0]=0.2;//把指针当做数组名去使用即可,C++将数组名解释为数组第一个元素的地址
p3[1]=0.5;
p3[2]=0.8;
p3=p3+1;//对于数组名来说,是一个常量,不可以进行加减运算,但对于指针来说是个变量,于是可以。

//Note, because the above operation makes p3 point to the address of the second element of the array, and it should be deleted from the first address when it needs to be deleted next, so the -1 operation is required (or mark the first address with a pointer in advance for subsequent delete operation)

p3=p3-1;
delete []p3;
return 0;

}

Episode:

When two pointers to strings need to be copied, the strcpy function should be used

Often used for initialization of string char arrays

strcpy(ps,animal);//将animal指向的字符串内容粘贴至ps所指字符串(需要提前确保内存空间足够)

The strncpy function, which accepts a third parameter, the number of characters to copy

strncpy(ps,animal,19);

Note that here we assume that the length of the ps array is 20, and the length of the animal array is greater than 20. Since the length of the latter exceeds the former, if there is no restriction, the strncpy function will not add '\0' to the last digit. Therefore, the length needs to be set to 19

ps[19]='\0';//手动补全空字符

Warning: You should use strcpy() or strncpy() instead of the assignment operator to copy strings to arrays

//strcpy
strcpy(p,"Hello");
cout<<*p<<endl; //只是输出p指向的字符串的第一个字符!
cout<<p<<endl; //输出p指向的字符串!
delete[] p;

    • Use new to open up array space

One-dimensional: int *a = new int[100];//Open up an integer array space with a size of 100

Two-dimensional: int **a = new int[5][6]

3D and beyond: and so on.

General usage: new type [initial value]

If the size of the array is uncertain, you can do the following

#include <iostream>
using namespace std;

int main()
{
    int size;
    cout << "Enter the size of the array: ";
    cin >> size;
    int *p = new int[size];
    // Use the array
    delete[] p;
    return 0;
}

Typical application

#include<iostream>
#include<cstring>
using namespace std;
char* getname();
int main()
{
char*name;
name=getname();
cout<<name<<"at"<<(int*)name<<"\n";
delete[]name;
name=getname();
cout<<name<<"at"<<(int*)name<<"\n";
delete[]name;
return 0;
}
char* getname()
{
char temp[80];
cout<<"Enter last name";
cin>>temp;
char* pn=new char[strlen(temp)+1];
strcpy(pn,temp);
return pn;

}
Notice:

When using dynamic arrays, you need to ensure that the array size is legal, and you need to ensure that dynamically allocated memory can be released.

To avoid memory leaks, you should delete dynamically allocated memory when an exception occurs.

At the same time, a common misunderstanding is:

The sizeof function is used in C++ to get the size of a variable or type, but it cannot be used to get the length of a dynamic array. Because the size of a dynamic array is allocated at runtime, while sizeof is done at compile time.

If you want to get the length of the dynamic array, you can record it when creating the array, or pass in a variable to record the size of the array when calling new.

like:

int size = 10;
int *p = new int[size];
// do something with the array
cout << "The size of the array is: " << size << endl;


//or


int size;
cout << "Enter the size of the array: ";
cin >> size;
int *p = new int[size];
// do something with the array
cout << "The size of the array is: " << size << endl;
    • Another method is to use vector in STL, because vector encapsulates new and delete, and it maintains the size itself, we can directly use vectorName.size() to get it.

  • A vector in the STL is a dynamic array that provides similar functionality to a dynamic array, but also provides some additional features, such as automatically growing the size of the array as the number of elements increases.

For example, if you want to create a vector of ints, you can write:

#include <vector>
using namespace std;

int main()
{
    vector<int> v;
    // Use the vector
    cout<<"The size of vector is: "<<v.size()<<endl;
    return 0;
}

Vector internally maintains the number of elements without manual recording.

When you need to add elements to the vector, you can use the push_back() function:

v.push_back(1);
v.push_back(2);

This makes it possible to obtain the size of a dynamic array at runtime without having to use the sizeof function.

Vector is safer than dynamic array because it maintains size information and automatically releases memory, avoiding memory leaks.

It should be noted that vector will automatically reallocate memory when there is not enough space, which means that the pointer to the vector memory block may change, so the vector pointer cannot be stored in the pointer array.

3. Use new to create dynamic structures

Basic format:

inflatable* ps=new inflatable;

Note: Since structures created in this way have no names, you cannot use "." to get member functions

So we need to use the "->" operator

like:

ps->price;//被指向的结构的price成员

Simply put: if you use the structure name. then apply"."

If it is a pointer, use "->"

(remember to delete)

To be continued......

Guess you like

Origin blog.csdn.net/holdon_yes/article/details/128670543