- 指针的算术
指针变量(地址的值)加1后,增加的量等于它指向的数据类型的字节数。例:// PointerTest10.cpp : 定义控制台应用程序的入口点。 // #include "stdafx.h" #include <string> #include <iostream> using namespace std; int _tmain(int argc, _TCHAR* argv[]) { int a = 1; string str = "哦豁"; char c = 'c'; float f = 1.0; //显示各个数据类型的长度 cout << "int类型的数据长度为" << sizeof(int) << endl; cout << "string类型的数据长度为" << sizeof(string) << endl; cout << "char类型的数据长度为" << sizeof(char) << endl; cout << "float类型的数据长度为" << sizeof(float) << endl; cout << "----------------------------------------------------------------------------" << endl; //以16进制的方式显示地址,加void*的目的是明确地告诉cout,这是一个地址,不要当做字符串显示 cout << "a的地址是:" << (void*)&a << ",a的地址+1是:" << (void*)(&a + 1) << endl;//void*优先级高于+1,因此+1部分需要加括号 cout << "str的地址是:" << (void*)&str << ",str的地址+1是:" << (void*)(&str + 1) << endl; cout << "c的地址是:" << (void*)&c << ",c的地址+1是:" << (void*)(&c + 1) << endl; cout << "f的地址是:" << (void*)&f << ",f的地址+1是:" << (void*)(&f + 1) << endl; cout << "----------------------------------------------------------------------------" << endl; //以10进制的方式显示地址,更清晰 cout << "a的地址是:" << (long long)&a << ",a的地址+1是:" << (long long)(&a + 1) << endl; cout << "str的地址是:" << (long long)&str << ",str的地址+1是:" << (long long)(&str + 1) << endl; cout << "c的地址是:" << (long long)&c << ",c的地址+1是:" << (long long)(&c + 1) << endl; cout << "f的地址是:" << (long long)&f << ",f的地址+1是:" << (long long)(&f + 1) << endl; system("pause"); }
- 数组的地址
(1)数组在内存中占用的空间是连续的。
(2)C++将数组名解释为数组第0个元素的地址。
(3)数组的第0个元素的地址与数组首地址是相同的
(4)数组第n个元素的地址时:数组首地址+n
(5)C++编译器把数组名[下标]解释为*(数组首地址+下标)
例:int arr[5]; cout << "arr的值是:" << (long long)arr << endl; cout << "arr的地址是:" << (long long)&arr << endl; cout << "arr[0]的地址是:" << (long long)&arr[0] << endl; cout << "arr[1]的地址是:" << (long long)&arr[1] << endl; cout << "arr[2]的地址是:" << (long long)&arr[2] << endl; cout << "arr[3]的地址是:" << (long long)&arr[3] << endl; cout << "arr[4]的地址是:" << (long long)&arr[4] << endl; cout << endl; int* p = arr;//声明一个指针,用数组arr给指针赋值 cout << "p的值是:" << (long long)p << endl; //对p进行数学运算 cout << "p+0的值是:" << (long long)(p+0) << endl; cout << "p+1的值是:" << (long long)(p+1) << endl; cout << "p+2的值是:" << (long long)(p+2) << endl; cout << "p+3的值是:" << (long long)(p+3) << endl; cout << "p+4的值是:" << (long long)(p+4) << endl; system("pause");
对指针解引用,同样可以访问地址中的数据:
int arr1[5] = {1,7,8,5,2}; cout << "arr1[0]的值是:" << *(arr1+0) << endl; cout << "arr1[1]的值是:" << *(arr1 + 1) << endl; cout << "arr1[2]的值是:" << *(arr1 + 2) << endl; cout << "arr1[3]的值是:" << *(arr1 + 3) << endl; cout << "arr1[4]的值是:" << *(arr1 + 4) << endl; cout << endl; int* p1 = arr1; cout << "p1+0的值是:" << *(p1 + 0) << endl; cout << "p1+1的值是:" << *(p1+1) << endl; cout << "p1+2的值是:" << *(p1+2) << endl; cout << "p1+3的值是:" << *(p1+3) << endl; cout << "p1+4的值是:" << *(p1+4) << endl;
-
数组的本质
数组是占用连续空间的一块内存,数组名被解释为数组第0个元素的地址。C++操作这块地址有两种方法,数组解释法和指针表示法,他们是等价的。 -
数组名不一定会被解释为地址
(1)多数情况下,C++将数组名解释为数组第0个元素的地址,但是,将sizeof运算符用于数组名时,将返回整个数组占用内存空间的字节数。
(2)可以修改指针的值,但是数组名是常量,不可修改。