[C puzzle book] Pointers and Arrays

时间:2021-03-19 21:42:01
#include <stdio.h>

#define PR(format,value) printf(#value"= %"#format"\t",(value))
#define NL putchar('\n')

#define PRINT1(f,x1) PR(f,x1), NL
#define PRINT2(f,x1,x2) PR(f,x1), PRINT1(f,x2)
#define PRINT3(f,x1,x2,x3) PR(f,x1), PRINT2(f,x2,x3)
#define PRINT4(f,x1,x2,x3,x4) PR(f,x1), PRINT3(f,x2,x3,x4)
#include "defs.h"

int a[]={0,1,2,3,4};

int main(void)
{
    int i,*p;
    for(i=0;i<=4;i++)
        PR(d,a[i]);
    NL;

    for(p=&a[0];p<=&a[4];p++)
        PR(d,*p);
    NL; NL;

    for(p=&a[0],i=1;i<=5;i++)
        PR(d,p[i]);
    NL;

    for(p=a,i=0;p+i<=a+4;p++,i++)
        PR(d,*(p+i));
    NL;NL;

    for(p=a+4;p>=a;p--) 
        PR(d,*p);
    NL;
    for(p=a+4,i=0;i<=4;i++)
        PR(d,p[-i]);
    NL;

    for(p=a+4; p>=a;p--)
        PR(d,a[p-a]);
    NL;


}
//Simple array and pointer
#include "defs.h"

int a[] = {0,1,2,3,4};
int *p[]={a,a+1,a+2,a+3,a+4};

int **pp=p;

int main(void)
{
    PRINT2(d,a,*a);
    PRINT3(d,p,*p,**p);
    PRINT3(d,pp,*pp,**pp);
    NL;

    pp++;  PRINT3(d,pp-p,*pp-a,**pp);
    *pp++; PRINT3(d,pp-p,*pp-a,**pp);
    *++pp; PRINT3(d,pp-p,*pp-a,**pp);
    ++*pp; PRINT3(d,pp-p,*pp-a,**pp);
    NL;

    pp=p;
    **pp++; PRINT3(d,pp-p,*pp-a,**pp);
    *++*pp; PRINT3(d,pp-p,*pp-a,**pp);
    ++**pp; PRINT3(d,pp-p,*pp-a,**pp);
}
//Array of pointers
#include "defs.h"

int a[3][3] ={
    {1,2,3},
    {4,5,6},
    {7,8,9}
};

int *pa[3] ={ a[0],a[1],a[2]};

int *p=a[0];

int main(void)
{
    int i;
    for(i=0;i<3;i++)
        PRINT3(d,a[i][2-i],*a[i],*(*(a+i)+i));
    NL;

    for(i=0;i<3;i++)
        PRINT2(d,*pa[i],p[i]);

    
}
#include "defs.h"

char *c[] = {
    "ENTER", "NEW","POINT","FIRST"};
char **cp[]={c+3,c+2,c+1,c};
char ***cpp=cp;

int main(void)
{
    printf("%s",**++cpp);
    printf("%s",*--*++cpp+3);
    printf("%s",*cpp[-2]+3);
    printf("%s\n",cpp[-1][-1]+1);
    return 0;
}