C指针原理(17)-C指针基础

指针本身也是一种变量,支持常用的运算。比如加、减

#include <stdio.h>

int main(void){

        int i;

        char x[20]="0123456789ABCDEFGHIJ";

        for (i=0;i<20;i++){

        printf("x[%d]:%c\n",i,x[i]);

        }

        char *p_x;

        for (p_x=&x[0];p_x<&x[20];p_x++){

                printf("%c",*p_x);

        }

        printf ("\n");

        for (p_x=x;p_x<(x+20);p_x++){

                printf("%u:%c\n",p_x,*p_x);

        }

        return 1;

}

在后面增加的内容p_x直接指向了x,然后通过x++来移动指针,终止for循环的条件是p_x<(x+20),x+20指向了数组的结尾处后面的内存位置,这个内存位置永远不会被访问,所以这样引用是安全的。

最后这段代码将每个字符的内存地址以及字符本身输出.

myhaspl@myhaspl:~ % make clean

rm mytest

myhaspl@myhaspl:~ % make

cc test3.c -o mytest

myhaspl@myhaspl:~ % ./mytest

...........

...........

4294957776:0

4294957777:1

4294957778:2

4294957779:3

4294957780:4

4294957781:5

4294957782:6

4294957783:7

4294957784:8

4294957785:9

4294957786:A

4294957787:B

4294957788:C

4294957789:D

4294957790:E

4294957791:F

4294957792:G

4294957793:H

4294957794:I

4294957795:J

myhaspl@myhaspl:~ % 

猜你喜欢

转载自blog.51cto.com/13959448/2325042