(type)<expression>
其中,type为类型描述符,如int,float等。<expression>为表达式。经强制类型转换运算符运算后,返回一个具有type类型的数值,这种强制类型转换操作并不改变操作数本身,运算后操作数本身未改变,例如:
int nVar=0xab65;
char cChar=char (nVar);
上述强制类型转换的结果是将整型值0xab65的高端两个字节删掉,将低端两个字节的内容作为char型数值赋值给变量cChar,而经过类型转换后nVar的值并未改变。i
结构体和数组的强制转换
c语言中的结构体不能直接进行强制转换,只有结构体指针才能进行强制转换。
例子:
#include <stdio.h>
typedef struct _name{
int age;
char name[20];
}PERSON;
typedef struct _test{
int age;
char name[20];
}TEST;
void fun(PERSON *one)
{
printf("输出名字%s,输出年龄%d\n",one->name,one->age);
}
int main()
{
PERSON man={19,"小明"};
PERSON *man1;
TEST test={20,"小红"};
TEST *test1;
//test1=(PERSON)test; 这种强制转换时错误的,必须用结构体指针转换
test1=(PERSON*)&test;
//test1=(void*)&test;
//或者使用void *
printf("输出名字%s,输出年龄%d\n",test1->name,test1->age);
}
结构体和数组的强制转换
c语言中的结构体和数组不能直接进行强制转换,只有结构体指针才能进行强制转换。
例子:
#include <stdio.h>
typedef struct _name{
int age;
char name[20];
}PERSON;
typedef struct _test{
int age;
char name[20];
}TEST;
void fun(PERSON *one)
{
printf("输出名字%s,输出年龄%d\n",one->name,one->age);
}
int main()
{
PERSON man={19,"小明"};
PERSON *man1;
TEST test={20,"小红"};
TEST *test1;
//test1=(PERSON)test; 这种强制转换时错误的,必须用结构体指针转换
test1=(PERSON*)&test;
//test1=(void*)&test; //或者使用void *
printf("输出名字%s,输出年龄%d\n",test1->name,test1->age);
}
数组强制转换
#include <stdio.h>
int main()
{
int i=0;
int a[2]={0x11223344,0x55667788} ;
char b[2];
char *p;
//b=a; //这里错误, 因为数组中 强制转换中只能用 指针进行强制转换
p=(char*)a;
for(i=0;i<8;i++)
printf("%x\n",p[i]);
//printf("输出名字%s,输出年龄%d\n",test1->name,test1->age);
}
其中,type为类型描述符,如int,float等。<expression>为表达式。经强制类型转换运算符运算后,返回一个具有type类型的数值,这种强制类型转换操作并不改变操作数本身,运算后操作数本身未改变,例如:
int nVar=0xab65;
char cChar=char (nVar);
上述强制类型转换的结果是将整型值0xab65的高端两个字节删掉,将低端两个字节的内容作为char型数值赋值给变量cChar,而经过类型转换后nVar的值并未改变。i
结构体和数组的强制转换
c语言中的结构体不能直接进行强制转换,只有结构体指针才能进行强制转换。
例子:
#include <stdio.h>
typedef struct _name{
int age;
char name[20];
}PERSON;
typedef struct _test{
int age;
char name[20];
}TEST;
void fun(PERSON *one)
{
printf("输出名字%s,输出年龄%d\n",one->name,one->age);
}
int main()
{
PERSON man={19,"小明"};
PERSON *man1;
TEST test={20,"小红"};
TEST *test1;
//test1=(PERSON)test; 这种强制转换时错误的,必须用结构体指针转换
test1=(PERSON*)&test;
//test1=(void*)&test;
//或者使用void *
printf("输出名字%s,输出年龄%d\n",test1->name,test1->age);
}
结构体和数组的强制转换
c语言中的结构体和数组不能直接进行强制转换,只有结构体指针才能进行强制转换。
例子:
#include <stdio.h>
typedef struct _name{
int age;
char name[20];
}PERSON;
typedef struct _test{
int age;
char name[20];
}TEST;
void fun(PERSON *one)
{
printf("输出名字%s,输出年龄%d\n",one->name,one->age);
}
int main()
{
PERSON man={19,"小明"};
PERSON *man1;
TEST test={20,"小红"};
TEST *test1;
//test1=(PERSON)test; 这种强制转换时错误的,必须用结构体指针转换
test1=(PERSON*)&test;
//test1=(void*)&test; //或者使用void *
printf("输出名字%s,输出年龄%d\n",test1->name,test1->age);
}
数组强制转换
#include <stdio.h>
int main()
{
int i=0;
int a[2]={0x11223344,0x55667788} ;
char b[2];
char *p;
//b=a; //这里错误, 因为数组中 强制转换中只能用 指针进行强制转换
p=(char*)a;
for(i=0;i<8;i++)
printf("%x\n",p[i]);
//printf("输出名字%s,输出年龄%d\n",test1->name,test1->age);
}