C学习:const修饰、结构体指针及位域使用
const的临近修饰用法
- const在前面
const int nValue; // nValue是const
const char *pContent; // *pContent是const, pContent可变
const char* const pContent; // pContent 和 *pContent都是const
- const在后面,与上面的声明对等
int const nValue; // nValue是const
char const * pContent; // *pContent是const, pContent可变
char* const pContent; // pContent是const, *pContent可变
char const* const pContent; // pContent 和 *pContent都是const
根据上面的例子和注释简单总结为:const跳过其后的数据类型修饰其后的变量(括号可以限定修饰范围)。
如上面的const char *pContent; 语句,const修饰后面的“*pContent”,故而*pContent是const的;
又如语句“char* const pContent; ”,const修饰其后的“pContent”,故而pContent是const的。
结构体指针
结构体指针的用法
通过结构体指针变量获得其结构体变量的成员变量有两种方式:
- (*结构体指针变量). 成员变量
- 结构体指针变量->成员变量
其中,“.”为取结构体成员变量的运算符。
另外C语言中引入了新的运算符“->”用于结构体指针变量直接获得结构体变量的成员变量
typedef struct BirthDay
{
int year;
int month;
int day;
} BirthDay_T;
typedef struct Stu
{
char name[20];
long num;
BirthDay_T birthday;
} Stu_T;
int main()
{
...
Stu_T student = {0};
Stu_T *pStu; /*定义结构体类型指针*/
//pStu = malloc(sizeof(Stu_T)); /*为指针变量分配安全的地址*/
printf("Input name, number, year, month, day:\n");
scanf("%s", student.name);
scanf("%ld", student.num);
...
pStu = &student;
student.name = "wangerqiang" /* error */
...
}
pStu = &student是将student的地址存储在结构体指针变量pStu中,*pStu代表指针变量student中的内容,因此*pStu 和student等价,所以:
(*pStu).num = student.num;
(*pStu).birthday.year = student.birthday.year;
等价于
pStu->num = student.num;
pStu->birthday.year = student.birthday.year;
另外语句student.name = “wangerqiang”编译报错,需要注意的是student.name是数组名,代表数组的首地址(地址常量),给常量赋值是非法的。
指向结构体数组的指针的使用
int main()
{
...
Stu_T student[100] = {0};
Stu_T *pStu; /*定义结构体类型指针*/
...
pStu = &student;
...
pStu++;
...
}
以上程序对结构体数组student元素的引用可采用三种方法:
- 地址法
student+i和pStu+i均表示数组第i个元素的地址,数组元素成员的引用形式为:
(student+i)->name, (student+i)->num 和 (pStu+i)->name, (pStu+i)->num等.
student+i 和 pStu+i 及 &student[i]意义相同。
- 指针法
若pStu指向数组的某一个元素,则pStu++就指向其后续元素。
- 指针的数组表示法
pStu = &student,pStu指向数组student,pStu[i]表示数组的第i个元素,其效果与student[i]等同。
对数组成员的引用描述为:pStu[i].name, pStu[i].num。
位域的使用
typedef struct
{
unsigned short u16_1 : 12;
unsigned short u16_2 : 4;
} U16BitField_Type;
typedef struct
{
unsigned char u8_1 : 6;
unsigned char u8_2 : 2;
} U8BitField_Type;
int main()
{
U16BitField_Type struc16 = {0};
U8BitField_Type struc8 = {0};
unsigned short *pU16 = NULL;
unsigned char *pU8 = NULL;
struc16.u16_1 = 0x0A98;
struc16.u16_2 = 0x000F;
pU16 = &struc16;
struc8.u8_1 = 0x3A;
struc8.u8_2 = 0x03;
pU8 = &struc8;
printf("struc16.u16_1:0x%X struc16.u16_2:0x%X *pU16:0x%X \n", struc16.u16_1, struc16.u16_2, *pU16);
printf("struc8.u8_1:0x%X struc8.u8_2:0x%X *pU8:0x%X \n", struc8.u8_1, struc8.u8_1, *pU8);
return 0;
}
结果是*pU16 = 0xFA98; *pU8 = 0xFA;
注:测试处理器环境为小端