c指针的强制转换(cast)

1.类型转化包含两种形式:

    自动隐式转换

    强制显式转换

2.自动隐式转换:

        。低类型会自动向高类型转换:      

char a, b, c;
...
a = b + c;
整型算术运算会自动缺省整型类型精度进行计算,首先对b,c进行提升为int型,计算完在截断为char型。

char a, b;
int c;
double  f, g;
c = a + b;
g = f + c;

计算c时会将a和b转换为int型;

计算g时会将f和c同时转换为float型;

.显示类型转换(只说指针的):

#include 

int main(int argc, char argv[])
{
        int iwoo, *pint;
        char cwoo, *pchar;

        /* the first pintf will print: 0x134513424, and this is a long type
           while the os is  32b */
        printf("pint addr is 0x%x\n", pint);

        printf("int length is %d\n", sizeof(int));
        printf("pchar addr is 0x%x\n", pchar);
        printf("char length is %d\n", sizeof(char));

        /*
         *(int *)0x134513424 = 8;
          if like this, the gcc may show : 
        the integer constang is too large for the 'long' type ;
        *(int *)0x134513424ll = 8;there is no warning, but when you 
        use:./point.o, it will show segmentation fault;
        */
        iwoo = 1025;
        pint = &iwoo;
        printf("var pint pointing is 0x%08x\n", *pint);
        printf("pint addr is 0x%x\n", pint);

        pchar = (char *)pint;
        printf("var0 pchar pointing is 0x%02x\n", *pchar);
        printf("var1 pchar pointing is 0x%02x\n", *(pchar + 1));
        printf("var2 pchar pointing is 0x%02x\n", *(pchar + 2));
        printf("var3 pchar pointing is 0x%02x\n", *(pchar + 3));

	return 0;
}
运行显示:

[wang2@wuhz test]$ ./point.o
pint addr is 0x134513424
int length is 4
pchar addr is 0x10
char length is 1
var pint point is 0x00000401

var pchar point is 0x01
var pchar point is 0x04
var pchar point is 0x00
var pchar point is 0x00
1025十六进制就是0x00000401
输出应该告诉我们:
指针应该是int型的,强制类型转换是告诉编译器应该以何种方式访问指针:*pint就是访问pint地址处
连续的4(sizeof(int))个字节;而*pchar是访问pchar地址处的一(sizeof(char))个字节;...
 
   
 
   
 
   
 
   
 
   
 
   
 
   
 
   
 
   
 
   
 
   
 
   
 
   
 
  

你可能感兴趣的:(Linux,C)