指向整形数组的指针

逍遥云 posted @ 2010年12月10日 23:48 in c/c++ with tags c pointer to array 数组针指 , 1731 阅读
    int a[10];
    memset(a, 0, sizeof(a));
    int *pt = a;
    *pt = 2;
    pt[1] = 1;
    pt++;
    printf("*pt = %d, pt[-1] = %d, sizeof(a) = %d\n", *pt, pt[-1], sizeof(a));
    --pt;
    *(pt + 10) = 77;
    
    int (*p)[10] = &a;
    memset(*p, 0, sizeof(*p));
    (*p)[0] = 10;
    (*p)[1] = 9;
    printf("**p = %d, (*p)[1] = %d, sizeof(*p) = %d\n", **p, (*p)[1], sizeof(*p));
    p++; //跳过40个地址长度,即a[10]连续地址之后,
    printf("**p = %d\n", **p); //得到77这个值
    --p; //为不影响后面的结果,修正p的指向为a[0]的地址;
    
    int (**pa)[10] = &p;
    memset(**pa, 0, sizeof(**pa));
    (**pa)[0] = 50;
    (**pa)[1] = 30;
    printf("***pa = %d, (**pa)[1] = %d, sizeof(**pa) = %d,\n", ***pa, (**pa)[1], sizeof(**pa));

    int **pp = &p;
    memset(*pp, 0, sizeof(**pa));
    (*pp)[0] = 31;
    (*pp)[1] = 32;
    (*pp)++;
    printf("**pp = %d, (*pa)[-1] = %d\n", **pp, (*pp)[-1]);
    --(*pp);

    int ***ppp = &pp;
    memset(**ppp, 0, sizeof(**pa));
    ***ppp = 40;
    (**ppp)[1] = 99;
    (**ppp)++;
    printf("***ppp = %d, (**ppp)[-1] = %d\n", ***ppp, (**ppp)[-1]);
    --(**ppp);

    int ****pppp = &ppp;
    memset(***pppp, 0, sizeof(**pa));
    ****pppp = 50;
    (***pppp)[1] = 100;
    (***pppp)++;
    printf("****pppp = %d, (***pppp)[-1] = %d\n", ****pppp, (***pppp)[-1]);

 

主要还是在于如何理解解引用,++操作只能用于指针变量,而*p与**pa却明确指向一个数组,如果*p++或者**pa++的话,gcc编译器会出现:

error: lvalue required as increment operand

这样的错误,然而p与*pa指向一个数组的首地址,如果使用++或--的话,就会有跨度,即直接跨过数组地址长度而指向下一块,对的,有点块的感觉。


登录 *


loading captcha image...
(输入验证码)
or Ctrl+Enter