[C++]C++小笔记 --- Pointers, Vectors and Array Objects

本文深入浅出地介绍了C++中的指针概念及其应用,包括指针的基本操作、动态内存分配与释放、指针数组及指向指针的指针等核心内容,并对比了内置数组与向量在内存中的不同表现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

指针介绍:

在开始介绍指针之前,现需要了解两个符号: &寻址和*取值符号;
int n = 10     //&n取的变量n的地址
cout <<"The address of n is" << &n << endl;

int * pn = &n;   //指针pn指向n的地址,*pn是pn指向的地址的值。
cout <<"The value that pn points to is" << *pn<<endll

int * pt;

pt is a pointer that points to a "int" type value.

double * pd;

pd is a pointer that points to a "double" type value.

New and Delete a pointer

The pointers that we mentioned above all points to a memory location that were declared and initialised by other variables. 
Pointers can points to a memory location that was declared and initialised by itself using new.

Typename * pointerName = new Typename;

int * pn = new int;
*pn = 100;

pointers that are created by new must be deleted later after use. The delete only free the memory that pn points, it does not delete the pointer itself.
delete pn;


Create array dynamically

To create a dynamic array in C++, 
int * pn = new int[10]; //new Type-of-array No-of_elements
*pn = 1;  //The first element
pn[0] = 1;  //first element
pn[1] = 2;  //second
*(pn+1) =2;  //second

The new operator returns the address of the first element of the array. The brackets tells the program that to remove the whole array but not the pointer itself.
delete[] pn;

The name of an array is the address of the first element of that array, and alias, the address of the array.

int ar[3] = {1,2,3};

In short, you should observe these rules when you usenew and delete:

  • Don’t use deleteto free memory thatnewdidn’t allocate.
  • Don’t use deleteto free the same block of memory twice in succession.nUsedelete []if you usednew []to allocate an array.
  • Use delete(no brackets) if you usednewto allocate a single entity.
  • It’s safe to applydeleteto the null pointer (nothing happens). 
int * pn = new int[10]; // new int[10] creates a array of 10 int and return the address of the first element of the array.
pn[1] == *(pn+1)  //The value of the second element of the array


关键字new可以用来声明/为一个类型获取内存空间。所以如果一个

struct Tapstry { int x, int y};

Tapstry * tps = new Tapstry; // tps pointer points to the address of type Tapstry struct.

tps->x = 1;

(*tps).y = 2;

The C-style string

C style string是指字符串是以字符数组的方式保存,在字符串结束处以'\0' 表示结束。
char chars[] = {'H','e','l','l','o','\0'};
char chars[] = "Hello" //implicate add '\0' at the end of Hello

char chars[] = "tests";
char chars_b[] = {'H','e','l','l','o','\0'};
cout<<chars<<chars_b<<endl;

Result:

testsHello

其实可以使用指针的方式来使用string. "HelloString" 

	const char * aaa = "HelloString";  
	char * css = new char[strlen(aaa) + 1];
	strcpy(css, aaa);
	cout << css << aaa << endl;
	delete[] css;

Result:

HelloStringHelloString

指针数组和指向指针的指针

int a = 10;
int b = 20;
const int * pa[2] = {&a, &b};
int ** pTop= pa;

pa是数组,他的元素是指针,pa也称作指针数组; const int表示pa的元素常量。 

       pTop    >      pa                 int
         0x..    /        0x...         ->     a
                            0x...        ->      b
pa也是一个指针,指向它的第一个元素,which is also a pointer, so pa is a pointer to a pointer. so that 
int ** pTop = pa;     
stands.

Vectors(C++ 98) and Array Objects(C++ 11)

Vector is  a dynamic class that its size can change during run time. It uses 'new' and 'delete' automatically, so that it stores on the HEAP.
Vector<Type> vector_variable_name(no_of_elems);

no_of_elems can be a variable as the size of the vector is resizable.

Array Object  is a fixed size and use stack as build-in array, but with more safety. To use Array object, we need to include <array> header.
array<TypeName, no_of_elems> array_obj_variable_name;

no_of_elems can not be a variable and must be a const number because array object is a fixed-size.

Array object can be assigned to another array object, well build-in array types can only be copied element-by-element.

void ChapterFour::showPointers() {
	double da[2] = {1.3, 2.4};
	int vsize = 2;
	vector<int> va(2);
	va[0] = 10;
	va[1] = 20;
	int ia[2] = {1,2};
	cout<< "value of build-in array da[1] "<< da[1] << " the address " << &da[1] <<endl;
	cout <<" value of build-in array ia[1] " << ia[1] << " the address " << &ia[1] << endl;
	cout <<" value of build-in array ia[-1] " << ia[-1] << " the address " << &ia[-1] << endl;
	cout <<" value of vector va[1] " << va[1] << " the address " << &va[1] << endl;
}

Result:
value of build-in array da[1] 2.4 the address 0x7fff3cda39e8
 value of build-in array ia[1] 2 the address 0x7fff3cda39f4
 value of build-in array ia[-1] 1073951539 the address 0x7fff3cda39ec
 value of vector va[-1] 20 the address 0xba5194

The result shows that:
  • the build-in array are stored on stack, and their locations are very close to each other
  • the vector are stored on heap and its address is different.
  • build-in array index have -1 

变量在内存中存储的方式

  1. 自动存储: 在方法中声明的变量是自动存储,保存在stack中, Last in, first out. 在退出方法返回时,内存被回收
  2. 静态存储,static variable. 从定义的地方开始到程序执行结束,全局有效。
  3. 动态存储,用new  和delete. 声明的变量保存在heap中。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值