1. 程式人生 > >C結構體中賦值使用的冒號和點號

C結構體中賦值使用的冒號和點號

根據論壇中,別人的回答,總結試驗的成果

1、其中位域列表的形式為: 型別說明符 位域名:位域長度

struct bs
{
 int a:8;
 int b:2;
 int c:6;
}data;
說明data為bs變數,共佔兩個位元組。其中位域a佔8位,位域b佔2位,位域c佔6位。


2、初始化結構的時候現在可以這樣寫:


(1)struct {
int a[3], b;
} hehe[] ={
 [0].a = {1,6,8},
 [1].b = 2
 };


含義,舉例:
#include <stdio.h>


struct {
int a[3], b;
} hehe[] ={
 [0].a = {1,6,8},
 [1].b = 2
 };


int main()
{
int i;
printf("結構體變數hehe[0]的引數如下\n");
for(i=0; i<3; i++)
printf("hehe[0].a[%d]=%d ", i, hehe[0].a[i]);
printf("hehe[0].b=%d\n\n", hehe[0].b);

printf("結構體變數hehe[1]的引數如下\n");
for(i=0; i<3; i++)
printf("hehe[1].a[%d]=%d ", i, hehe[1].a[i]);
printf("hehe[1].b=%d\n", hehe[1].b);

return 0;
}


列印結果:
構體變數hehe[0]的引數如下
hehe[0].a[0]=1 hehe[0].a[1]=6 hehe[0].a[2]=8 hehe[0].b=0
結構體變數hehe[1]的引數如下
hehe[1].a[0]=0 hehe[1].a[1]=0 hehe[1].a[2]=0 hehe[1].b=2
(2)struct {
int a, b, c, d;
} hehe =  {
.a = 1, 
.c = 3, 4, 
.b = 5
}  // 3,4 是對 .c,.d 賦值的


舉例:
#include <stdio.h>


struct {
int a, b, c, d;
}hehe={
.a = 1, 
.c = 3, 4, 
.b = 5
};//3,4 是對.c和.d的賦值
int main()
{
printf("結構體變數hehe的引數如下\n");

printf("hehe.a=%d ",  hehe.a);
printf("hehe.b=%d ",  hehe.b);
printf("hehe.c=%d ",  hehe.c);
printf("hehe.d=%d \n",  hehe.d);

return 0;
}
執行結果:
結構體變數hehe的引數如下
hehe.a=1 hehe.b=5 hehe.c=3 hehe.d=4