關於C語言結構體賦值(linux核心風格)

helloxchen發表於2010-11-17

1 對成員賦值.

例如結構體struct st1 {

int a;

int b;

int c;

}
1.1 用{}形式.
struct st1 st1 = {1,2,3);
1.2 linux kernel風格.
struct st1 st1 = {
.a = 1;
.b = 2;
};

//注 此風格(即在成員變數之前加點“.”),可以不按成員變數的順序進行賦值。如可以為

struct st1 st1 = {

.c = 3;
.a = 1;
.b = 2;
};

2 對整體賦值.
struct st1 a, b;
b = a;

3 結構體作為
函式返回值對另一個結構體賦值.
struct st1 func1();
struct st1 a = func1();

舉例:
[ctest]# vi t.c

#include

struct st1 {
int e1;
int e2;
};

struct st1 func1()
{
struct st1 h = { 77, 88};
return h;
}

int main()
{
struct st1 a = { 33, 44};
struct st1 b = {
.e1 = 55,
};
struct st1 c;
struct st1 d;
c = a;
d = func1();
printf("e1 e2 is %d %dn", a.e1, a.e2);
printf("e1 e2 is %d %dn", b.e1, b.e2);
printf("e1 e2 is %d %dn", c.e1, c.e2);
printf("e1 e2 is %d %dn", d.e1, d.e2);
return 0;
}
"t.c" 29L, 420C written
[ctest]# gcc -o a t.c
[ctest]# ./a
e1 e2 is 33 44
e1 e2 is 55 0
e1 e2 is 33 44
e1 e2 is 77 88

http://blog.163.com/a3563@126/blog/static/54675706200710134410126/

[@more@]

來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/24790158/viewspace-1041624/,如需轉載,請註明出處,否則將追究法律責任。

相關文章