指针的学习(下)

指针的指针

#include <cstdio>

int main(int argc, char *argv[]){
    int num = 520;
    int *p = &num;
    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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值