- 指针是一种存放内存地址的变量(所以也叫指针变量),注意指针概念在Java中被封装起来了即没有明确的指针的概念。
在Java中引用其实是指针的更上一层的应用。
- 任何变量都有内存地址(包括指针)
- 指针变量相应的数据类型,是指针所指向的内存单元存放的数据的数据类型。
- 声明
<数据类型>* <指针名>
用于取一个变量的地址(取址)
运算符“*”
以指针为 *** 作数,运算结果是其指针所指向地址的变量(取值)
“&”和“*”互为逆运算
*pa == *&*pa
pa == &a
*&pa == &a
**&pa == a
int a = 10, b = 20;
int* pa = &a, * pb = &b;
float c = 9.02f;
float* pc = &c;
cout << "&pa和&pb:"<< &pa << ", " << &pb << endl;
cout << "&a和&b:" << &a << ", " << &b << endl;
cout << "*pa和*pb:" << *pa << ", " << *pb << endl;
cout << "a和b:" << a << ", " << b << endl;
//cout << "地址pa&pb:" << endl << **pa << ", " << **pb << endl;//错误!!!
cout << "*&*pa和*&*pb:" << *&*pa << ", " << *&*pb << endl;
cout << "&*pa和&*pb:" << &*pa << ", " << &*pb << endl;
cout << "pa和pb:" << pa << ", " << pb << endl;
cout << "&a和&b:" << &a << ", " << &b << endl;
pa = &b; pb = &a;
cout << "*pa和*pb:" << *pa << ", " << *pb << endl;
*pa = 100; *pb = 200;
cout << "*pa和*pb:" << *pa << ", " << *pb << endl;
cout << "a和b:" << a << ", " << b << endl;
cout << "&*pa和&*pb:" << &*pa << ", " << &*pb << endl;
cout << "pa和pb:" << pa << ", " << pb << endl;
cout << "&a和&b:" << &a << ", " << &b << endl;
/*输出
&pa和&pb:00F6FCD0, 00F6FCC4
&a和&b:00F6FCE8, 00F6FCDC
*pa和*pb:10, 20
a和b:10, 20
*&*pa和*&*pb:10, 20
&*pa和&*pb:00F6FCE8, 00F6FCDC
pa和pb:00F6FCE8, 00F6FCDC
&a和&b:00F6FCE8, 00F6FCDC
*pa和*pb:20, 10
*pa和*pb:100, 200
a和b:200, 100
&*pa和&*pb:00F6FCDC, 00F6FCE8
pa和pb:00F6FCDC, 00F6FCE8
&a和&b:00F6FCE8, 00F6FCDC
*/
指针与数组
- 数组名表示数组在内存中的首地址
- 通常使用指针变量指向数组的首地址,就可以指向该数组(即可以访问该数组)
- 在c++中指针可以进行运算(如自增,加减运算当然要小心越界访问到未给程序分配的内存)
指针的运算
1)指针本身的运算(其实是地址移动)
2)指针所指向地址的变量的运算
int array1[] = { 10,9,3,1,4,5,0 };
int* array2 = array1;
cout << "sizeof(array1)/sizeof(*array1): " << sizeof(array1)/sizeof(*array1) << endl;//7
cout << "sizeof(array1)/sizeof(int): " << sizeof(array1) / sizeof(int) << endl;//7
cout << "sizeof(array2): " << sizeof(array2) << endl;//4
cout << "sizeof(*array2): " << sizeof(*array2) << endl;//4
cout << "sizeof(int): " << sizeof(int) << endl;//4
cout << "sizeof(array1): " << sizeof(array1) << endl;//28
cout << "sizeof(*array1): " << sizeof(*array1) << endl;//4
cout << *array1 << endl;//10
cout << *array2 << endl;//10
cout << array1[0] << endl;//10
cout << array2[0] << endl;//10
cout << *array1 + 1 << endl;//11
cout << *array2 + 2 << endl;//12
cout << *(array1 + 1) << endl;//9
cout << *(array2 + 2) << endl;//3
cout << array1 << endl;//004FFE00(array1的首地址)
cout << array2 << endl;//004FFE00(array1的首地址)
cout << array1 + 1 << endl;//004FFE00(array1[1]的地址)
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)