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

来源:互联网 发布:linux usleep 编辑:程序博客网 时间:2024/05/21 08:59

多维数组指针

指针是一个变量,它指向另一个变量的地址,指针本身的大小相同,但它指向变量的大小不一定相同,比如说char指针和int指针就不一样,32位系统中,char指针指向的变量仅有1字节,而int指针指向的变量有4个字节,这意味着将char指针指向int指针将有风险,值将被截断。比如:

//code:myhaspl@qq.com

#include <stdio.h>

int main(void){

        char *i;

        int x=127;

        i=(char*)&x;

        printf("%d",*i); 

        return 1;

}           

本博客所有内容是原创,如果转载请注明来源

http://blog.csdn.net/myhaspl/


上面程序中当x值可用1个字节容纳时,程序运行正常。

myhaspl@myhaspl:~ % ./mytest

127myhaspl@myhaspl:~ % make

cc test5.c -o mytest

myhaspl@myhaspl:~ % ./mytest

127

但当x值较大时(不在-128~127以内),就会出问题:

//code:myhaspl@qq.com

#include <stdio.h>

int main(void){

        char *i;

        int x=250;

        i=(char*)&x;

        printf("%d",*i); 

        return 1;

}  

myhaspl@myhaspl:~ % make

cc test5.c -o mytest

myhaspl@myhaspl:~ % ./mytest

-6m    

    

多维数组的指针定定义比一维数组更录活,因为它可以指定指向变量的最后一维的维数,下面定义的指针指向变量的大小是最后一维的5个元素,每次指针移动都以5个元素为单位:

//code:myhaspl@qq.com

#include <stdio.h>

int main(void){

        int i;

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

        int (*p_x)[5];

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

                printf("%d   ",*p_x[0]); 

        }

        return 1;

}      

myhaspl@myhaspl:~ % make

cc test6.c -o mytest

myhaspl@myhaspl:~ % ./mytest

1   6 

下面定义的指针仅指向一个元素 ,也通过改变指针指向变量的尺寸,将数组以5*2大小的方式进行访问,这样,编译器会给出警告,但能编译通过。

 //code:myhaspl@qq.com

#include <stdio.h>

int main(void){

        int i;

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

        int (*p_x)[2];

        for (p_x=x;p_x<&x[1][5];p_x++){

                printf("%d   ",*p_x[0]);

        }

        return 1;

}

myhaspl@myhaspl:~ % cc test8.c -o mytest                                          

test8.c: In function 'main':

test8.c:7: warning: assignment from incompatible pointer type

test8.c:7: warning: comparison of distinct pointer types lacks a cast

myhaspl@myhaspl:~ % ./mytest

1   3   5   7   9   

并不赞成这种做法,如果需要每隔2个元素进行访问,可以将指针指向多维数组的一个元素,每次移动加上2即可。

//code:myhaspl@qq.com

#include <stdio.h>

int main(void){

        int i;

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

        int *p_x=&x[0][0];

        for (;p_x<&x[1][5];p_x+=2){

                printf("%d   ",*p_x);

        }

        return 1;

}

 

myhaspl@myhaspl:~ % cc test7.c -o mytest                                          

myhaspl@myhaspl:~ % ./mytest

1   3   5   7   9