指针的指针
#include <cstdio>
int main(int argc, char *argv[]){
int num = 520;
int *p = #
int **pp = &p;
printf("num: %d\n", num);
printf("*p: %d\n", *p);
printf("**pp: %d\n", **pp);
printf("&p: %p, pp: %p\n", &p, pp);
printf("&num: %p, p: %p, *pp %p",&num, p, *pp);
return 0;
}
指针数组
#include <cstdio>
int main(int argc, char *argv[]){
char *cBooks[] = {
"c 程序设计语言",
"c 专家编程",
"c 和指针",
"c 陷阱 与 缺陷",
"c primer plus",
"带你学c带你飞"
};
char **byFishc;
char **jiayuloves[4];
byFishc = &cBooks[5];
jiayuloves[0] = &cBooks[0];
jiayuloves[1] = &cBooks[1];
jiayuloves[2] = &cBooks[2];
jiayuloves[3] = &cBooks[3];
printf("FishC 出版的书有:%s\n", *byFishc);
printf("小甲鱼喜欢的图书有:\n");
for (int i = 0; i < 4; ++i) {
printf("%s\n", *jiayuloves[i]);
}
return 0;
}
至少两个好处 1:只需要修改一处数据,2:避免重复分配内存
二维数组和指针
#include <cstdio>
int main(int argc, char *argv[]) {
int array[3][4] = {
{0, 1, 2, 3},
{4, 5, 6, 7},
{8, 9, 10, 11}
};
/*
* 此处的指针的变量
* **p 不能指向array
* 因为地址+1的改变量不同*/
int (*p)[4] = array;
/*
* 数组指针可以用来访问数组
* 因为其跨度一样*/
for (int i = 0; i < 3; ++i) {
for (int j = 0; j < 4; ++j) {
printf("%2d ", *(*(p + i) + j));
}
printf("\n");
}
return 0;
}
函数的参数传址
#include <cstdio>
void swap(int *x, int *y);
void swap(int *x, int *y) {
int temp;
printf("In swap,before: x = %d, y = %d\n", *x, *y);
temp = *x;
*x = *y;
*y = temp;
printf("In swap,after: x = %d, y = %d\n", *x, *y);
}
int main(int argc, char *argv[]) {
int x = 3;
int y = 5;
printf("In main, before: x = %d, y = %d\n", x, y);
swap(&x, &y);
printf("In main, after: x = %d, y = %d\n", x, y);
return 0;
}
数组参数传递
#include <cstdio>
void get_array(int a[10]);
void get_array(int a[10]){
a[5] = 520;
for (int i = 0; i < 10; ++i) {
printf("a[%d] = %d\n", i, a[i]);
}
}
int main(int argc, char *argv[]){
int a[10] = {1,2,3,4,5,6,7,8,9,0};
get_array(a);
printf("in main, again========================\n");
/*
* 在main中a[5]的值同样改为520
* 数组参数传递是传递地址*/
for (int i = 0; i < 10; ++i) {
printf("a[%d] = %d\n", i, a[i]);
}
return 0;
}
#include <cstdio>
void get_array(int b[10]);
void get_array(int b[10]) {
printf("sizeof b: %d\n", sizeof(b));
}
int main(int argc, char *argv[]) {
int a[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 0};
printf("sizeof a: %d\n", sizeof(a));
get_array(a);
return 0;
}