十二、 指针
12.1 指针定义
12.2 &和*的作用
12.3 指针应用
12.4 指针作为参数
12.5 指针作为返回值
#include<stdio.h>
int main()
{
int a = 10;
int b = 20;
int* p = &a;
*p = 100;
p = &b;
*p = 200;
int** pp = &p;
*pp = &a;
**pp = 1000;
*pp = &b;
**pp = 2000;
int*** ppp = &pp;
**ppp = &a;
***ppp = 5000;
**ppp = &b;
***ppp = 6000;
printf("%d", a);
return 0;
}
#include<stdio.h>
int main()
{
int a = 0;
int b = 0;
int c = 0;
int* p1 = &a;
int* p2 = &b;
int* p3 = &c;
*p1 = 100;
*p2 = 200;
*p3 = 300;
*p3 = *p1 + *p2;
*p3 = *p1 / *p2;
*p3 += 1;
printf("%d %d %d\n", *p1, *p2, *p3);
return 0;
}
- 指针的大小只与平台有关
32位sizeof( * )=4 64位sizeof( * )=8(字节)
#include<stdio.h>
void Swap_1(int* p1, int* p2)
{
int *tmp = p1;
p1 = p2;
p2 = tmp;
}
#if 0
void Swap_2(int* p1, int* p2)
{
int* tmp;
*tmp= *p1;
*p1 = *p2;
*p2 = *tmp;
}
#endif
void Swap(int* p1, int* p2)
{
int tmp;
tmp = *p1;
*p1 = *p2;
*p2 = tmp;
}
int main()
{
int a = 10;
int b = 20;
Swap(&a, &b);
printf("%d,%d\n", a, b);
return 0;
}
#include<stdio.h>
int main()
{
int arr[10] = { 1,2,3,4,5,6,7,8,9,10 };
for (int* p = arr; p <= &arr[9]; p++)
{
printf("%d ", *p);
}
char a = 'x';
char* p = &a;
return 0;
}
#include<stdio.h>
void Fun(int* p)
{
int* p1= p;
int* p2 = NULL;
int tmp;
tmp = *p1;
*p1 = *p2;
*p2 = tmp;
}
int main()
{
int a = 10;
int* p = &a;
Fun(p);
printf("%d\n", *p);
return 0;
}
断言
assert()(需要头文件#include<assert.h>) 断定表达式一定为真,如果为假程序崩溃,并报告错误位置。 release面向用户版本:assert后面需要进行条件判断。
void* 通用指针,泛型指针 void*无数据类型,不参与运算,不能++和解引用
赋值 | 通用指针 = 特定指针 | 特定指针 = 通用指针 |
---|
C++ | char* p; void* p1=p; | 不可以 (char* p; void* p1=p; int* p2=p1 (p2=p)数据类型不同 ) | C | char* p; void* p1=p; | void* p; char* p2=p; |
C++:NULL——0 C:NULL——((void*)0) 先有C后有C++,C++不支持void*赋值,故定义为0
|