Current location - Plastic Surgery and Aesthetics Network - Plastic surgery and medical aesthetics - Excuse me, in C++, int *p=new int(2) is to apply for a pointer field with a heap size of 4 for the p pointer, and the assignment is 2;
Excuse me, in C++, int *p=new int(2) is to apply for a pointer field with a heap size of 4 for the p pointer, and the assignment is 2;
int * p = new int[2];

The format of the statement is as shown in the above table, and there is no need for a pair of brackets at the end.

It means that two spaces of type int are allocated from the system heap, with 8 bytes in a row (in win32 system, int is 32 bits and 4 bytes), and the pointer p points to the starting address of the allocated space (that is, the address of the first array element). Generally, the value in the allocated new memory will not be automatically initialized to 0, but should be initialized by the programmer (memset or ZeroMemory function can be used, and loop statement can also be used).

When releasing the array space allocated by the new keyword, the format of the delete statement with [] is generally used (this example: delete [] p; ), the format without [] is used to release the memory space of a single variable allocated by new, while the delete without [] has no syntax error in releasing P in this example, and it will not be reported at compile time. In fact, it may only release the first element of the array, which may also be the reason why you pop up an error prompt at the end of running in VS20 10.

Because the syntax of C/C++ is flexible, the application and release of memory and the management of pointers are the most error-prone and difficult parts in C/C++, so it is suggested to read carefully the instructions related to memory allocation and release in C/C++ and write the code strictly according to the correct syntax.