C/C++ struct 用法與範例

本篇 ShengYu 介紹 C/C++ struct 結構用法與範例,struct 可以將不同資料類型集合在一起,通常將相關的變數類型放在同一個 struct 裡,也方便參數傳遞。

以下 C/C++ struct 結構的用法介紹將分為這幾部份,

  • C/C++ struct 基本用法
  • C/C++ struct 計算大小
  • struct 在 C/C++ 中的使用差異
  • C/C++ typedef struct 取別名

那我們開始吧!

C/C++ struct 基本用法

以下為 C/C++ struct 基本用法,以 student 有 id、age、name 屬性為例,struct 初始化有兩種寫法,
一種是先宣告 struct 後初始化,另一種是宣告 struct 時同時初始化的寫法,

cpp-struct.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
// g++ cpp-struct.cpp -o a.out
#include <stdio.h>
#include <string.h>

struct student {
int id;
int age;
char name[32];
};

int main() {
struct student s1;
s1.id = 10;
s1.age = 18;
strcpy(s1.name, "Tom");
printf("id: %d\n", s1.id);
printf("age: %d\n", s1.age);
printf("name: %s\n", s1.name);

struct student s2 = {11, 20, "Jerry"};
printf("id: %d\n", s2.id);
printf("age: %d\n", s2.age);
printf("name: %s\n", s2.name);

return 0;
}

輸出如下,

1
2
3
4
5
6
id: 10
age: 18
name: Tom
id: 11
age: 20
name: Jerry

定義 struct 順便宣告變數(s3)的寫法,

1
2
3
4
5
struct student {
int id;
int age;
char name[32];
} s3;

定義 struct 同時宣告多個變數(s3與s4)的話,用逗號連接即可,

1
2
3
4
5
struct student {
int id;
int age;
char name[32];
} s3, s4;

C/C++ struct 計算大小

計算該 struct 的大小,

cpp-struct2.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
// g++ cpp-struct2.cpp -o a.out
#include <stdio.h>
#include <string.h>

struct student {
int id;
int age;
char name[32];
};

int main() {
printf("int size: %d\n", sizeof(int));

struct student s1;
s1.id = 10;
printf("struct size: %d\n", sizeof(s1));

struct student s2;
s1.id = 11;
strcpy(s2.name, "shengyu");
printf("struct size: %d\n", sizeof(s2));

return 0;
}

輸出如下,

1
2
3
int size: 4
struct size: 40
struct size: 40

struct 在 C/C++ 中的使用差異

struct 在 C 中宣告時要寫 struct,在 C++ 宣告時就不需加上 struct,

1
2
struct student s1; // C/C++
student s2; // C++

C/C++ typedef struct 取別名

C/C++ 經常使用 typedef 把某個 struct 取一個別名,以下示範用 typedef 將 struct student 取一個 student_t 別名,之後宣告時就可以使用新的 student_t 別名,就可以省去加上 struct,藉此達到簡化宣告語法,

cpp-struct3.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
// g++ cpp-struct3.cpp -o a.out
#include <stdio.h>
#include <string.h>

typedef struct student {
int id;
int age;
char name[32];
} student_t;

int main() {
student_t s1;
s1.id = 123;
s1.age = 20;
printf("id: %d\n", s1.id);
printf("age: %d\n", s1.age);

return 0;
}

輸出如下,

1
2
id: 123
age: 20

另外還可以把 struct 的定義跟 typedef 分開寫,像這樣寫,

cpp-struct4.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
// g++ cpp-struct4.cpp -o a.out
#include <stdio.h>
#include <string.h>

struct student {
int id;
int age;
char name[32];
};

typedef struct student student_t;

int main() {
student_t s1;
s1.id = 123;
s1.age = 20;
printf("id: %d\n", s1.id);
printf("age: %d\n", s1.age);

return 0;
}

以上就是 C/C++ struct 的用法與範例介紹,
如果你覺得我的文章寫得不錯、對你有幫助的話記得 Facebook 按讚支持一下!

其它相關文章推薦
如果你想學習 C/C++ 相關技術,可以參考看看下面的文章,
C/C++ 新手入門教學懶人包
C/C++ enum 用法與範例
C/C++ union 用法與範例