C++

c++ 学习记录

C++ 基础

数组

初始化数组

int a[5] = {1,2,3,4,5};

{ } 中的个数不能超过5;

int a[5] = {1,2};

a = 1 2 0 0 0

不足5,后续则补充为0;

int a[] = {1,2,3,4,5};

缺失数组大小, 则初始化为{ } 内的元素个数大小

多维数组

int a[2][3] = {{1,2},{1,2,3}}

指针

指针是一个存储long 16进制的数据类型,& 地址运算符

用 asterisk * 定义一个指针

int *ip; // pointer to an integer
double *dp; // pointer to a double
float *fp; // pointer to a float
char *ch; // pointer to a character

动态内存

In a C++ program, memory is divided into two parts:

The stack: All of your local variables take up memory from the stack.

The heap: Unused program memory that can be used when the program runs to dynamically allocate the memory.

new int 在堆中分配一个int大小的内存,这时候返回一个指向该空间的地址;

该地址可以用 指针接收。

int *p = new int;
*p = 5;

The pointer p is stored in the stack as a local variable, and holds the heap‘s allocated address as its value. The value of 5 is stored at that address in the heap.

内存管理

本地变量自动管理

在heap上的需要手动处理动态分配的内存

For local variables on the stack, managing memory is carried out automatically.
On the heap, it’s necessary to manually handle the dynamically allocated memory, and use the delete operator to free up the memory when it’s no longer needed.

delete pointer;

上述语句释放pointer指向的内存

忘记释放使用new 分配的内存空间,会导致内存泄漏,直到程序被关闭。

动态内存分配内存

int *p = NULL; // Pointer initialized with null
p = new int[20]; // Request memory
delete [] p; // Delete array pointed to by p

空指针 Dangling Pointers

The delete operator frees up the memory allocated for the variable, but does not delete the pointer itself, as the pointer is stored on the stack.

Pointers that are left pointing to non-existent memory locations are called dangling pointers.

int *p = new int; // request memory
*p = 5; // store value

delete p; // free up the memory
// now p is a dangling pointer

p = new int; // reuse for a new address

The NULL pointer is a constant with a value of zero that is defined in several of the standard libraries, including iostream.
It’s a good practice to assign NULL to a pointer variable when you declare it, in case you do not have exact address to be assigned. A pointer assigned NULL is called a null pointer. For example: int *ptr = NULL;

定义指针的时候分配NULL

函数 Functions


本博客所有文章除特别声明外,均采用 CC BY-SA 4.0 协议 ,转载请注明出处!