#include<stdio.h> voidswap(int, int); intmain(void) { int a = 9, b = 13; printf("Before swapping\nValue of a: %d\nValue of b: %d\n", a, b); swap(a, b); printf("After swapping\nValue of a: %d\nValue of b: %d\n", a, b); return0; } voidswap(int x, int y) { int temp = x; x = y; y = temp; }
int *p; // initialize a pointer p = &x; // assign the memory location of x to p
该段代码中
*是解引用操作符, *p表示获取存储在p位置的数据
&是引用操作符,&x表示获取x变量的内存地址
指针的格式说明符是%p
1
scanf("The value store at %p is %d", p, *p);
所以,上述swap()函数的正确写法是:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
#include<stdio.h> voidswap(int*, int*); intmain(void) { int a = 9, b = 13; printf("Before swapping\nValue of a: %d\nValue of b: %d\n", a, b); swap(&a, &b); printf("After swapping\nValue of a: %d\nValue of b: %d\n", a, b); return0; } voidswap(int* x, int* y) { int temp = *x; *x = *y; *y = temp; }
指针的大小
在现代计算机中,所有的指针使用64bit存储,也就是8个字节
套娃指针
指针可以存储另一个指针的地址,但是这时候指针的类型就变成了**[type]
备注
int *p;等价于int* p;
好习惯
在解引用指针之前,强烈建议先检查指针是否为空
1 2 3 4 5 6 7 8 9 10 11 12 13
#include<stdio.h>
intmain() { int* p = NULL;
if (p == NULL) { printf("Cannot dereference it!\n"); } else { printf("The value at address p is %d.\n", *p); }
return0; }
6.4 作用域
老生常谈啦,变量必须得定义后才能使用,且只能在定义的作用域中生效,使用。
全局变量需要在main函数之前定义
作用域重叠
1 2 3 4 5 6 7 8 9 10 11
#include<stdio.h> intmain(void) { int i = 1; printf("Outer i = %d.\n", i); { int i = 2; printf("Inner i = %d.\n", i); } printf("Outer i = %d.\n", i); return0; }
while (true) { printf("Please type in an even number that is greater than 2: "); scanf("%d", &num); if (isInputValid(num)) { break; } else { printf("Invalid value!\n"); } }
printf("The result is %d", satisfyGoldBach(num)); return0; }