c++基础入门笔记10指针

137 阅读2分钟

定义: 数据类型* 变量名

int a = 4;
	int * p;//定义了p指针
	/*刚定义了一个指针,此时指针称为空指针,指向地址编号为0的空间,0-255是系统内存,不允许访问*/
	/*int * a=(int *)0x1100A;这是野指针,直接指向一个未被申请的地址,但我们没有
	访问权限,类似于宾馆开房间。*/
	p = &a;//p指向a的地址
	cout << &a << endl;
	cout << p << endl;
	cout << *p << endl;//代表p指针指向地址的内存
	cout<<sizeof();

结果

关于地址和内存,你可以想象一下图书馆。

const修饰指针

const修饰什么,什么就是常量!

p++代表的是指向下一个内存地址

地址传递

#include<iostream>
using namespace std;
void swap(int * p1,int * p2) {
	int temp = *p1;//与直接赋值不同,这里是通过交换地址来赋值
	*p1 = *p2;
	*p2 = temp;

}

int main() {
	int a = 1;
	int b = 2;
	swap(&a, &b);
	cout << a << " " << b << endl;//与之前的值传递不同,地址传递会通过形参来改变实参
	system("pause");

	return 0;
}

这里我们可以看到地址的重要性! 结果:

实列:

#include<iostream>
using namespace std;

void sort(int arr[],int len){//arr[]也可以用* arr代替,指针和数组名是很相似的
	for (int i = 0; i < len-1; i++) {
		for (int j = 0; j < len-1-i; j++) {
			if (arr[j] > arr[j + 1]) {
				int temp = arr[j];
				arr[j] = arr[j + 1];
				arr[j + 1] = temp;
			}
		}
	}
	for (int x = 0; x < len; x++) {
		cout << arr[x] << endl;
	}
}

int main() {
	int arr[10] = { 93,34,656,76,488,25,3344,43 };
	sort(arr,10);// sizeof(arr)/sizeof(arr[0])
	for (int x = 0; x < 10; x++) {
		cout << arr[x] << endl;
	}
	system("pause");
	return 0;
}