C語言之結構體

瀟灑Anthony發表於2020-12-09

宣告一個結構體型別的一般形式如下:
struct 結構體型別名
{
成員表列
};

結構體的型別可以有很多種,結構體型別中的成員由開發者自己定義,並且成員不用初始化。
另外,一個結構體成員可以屬於另一個結構體型別,例如:

 struct TIME
{
        int date;
        int month;
        int year;
        int hour;
        int min;
        int sec;
};

struct nmea_msg
{
    struct TIME utc;
    char gpssta;                                                             
    int longitude;                          
    int latitude;                                                 
    short speed;                       
    short altitude;                   
};

定義結構體變數的方法有三種:
1.先宣告結構體型別,再定義該型別變數:

一般形式為:
struct 結構體型別名
{
成員表列
};
struct 結構體型別名 變數名錶列;

例如:

struct UDP_Server_Thread_Para
{
	void *pData;
	int Len;
};
struct UDP_Server_Thread_Para  UDPThreadPara1,UDPThreadPara2;

一個在該定義方式下的程式例子:

#include<stdio.h>

struct UDP_Server_Thread_Para
{
    void *pData;
    int len;
};

int main()
{
   struct UDP_Server_Thread_Para UDPThreadPara1,UDPThreadPara2;
   
   UDPThreadPara1.pData = "hello";
   UDPThreadPara1.len = 1;

   UDPThreadPara2.pData = "world";
   UDPThreadPara2.len = 2;

   printf("UDPThreadPara1: %s, len %d\n", (char*)UDPThreadPara1.pData, UDPThreadPara1.len);

   printf("UDPThreadPara2: %s, len %d\n", (char*)UDPThreadPara2.pData, UDPThreadPara2.len);

   return 0;
}

2.在宣告的同時定義變數:

一般形式為:
struct 結構體型別名
{
成員表列
}變數名錶列;

例如:

struct UDP_Server_Thread_Para
{
	void *pData;
	int Len;
}UDPThreadPara1,UDPThreadPara2;

一個在該定義方式下的程式例子:

#include<stdio.h>

struct UDP_Server_Thread_Para
{
    void *pData;
    int len;
}UDPThreadPara1,UDPThreadPara2;

int main()
{
   UDPThreadPara1.pData = "hello";
   UDPThreadPara1.len = 1;

   UDPThreadPara2.pData = "world";
   UDPThreadPara2.len = 2;

   struct UDP_Server_Thread_Para UDPThreadPara3;	//新增該結構體型別變數
   UDPThreadPara3.pData = "!!!!";
   UDPThreadPara3.len = 3;

   printf("UDPThreadPara1: %s, len %d\n", (char*)UDPThreadPara1.pData, UDPThreadPara1.len);

   printf("UDPThreadPara2: %s, len %d\n", (char*)UDPThreadPara2.pData, UDPThreadPara2.len);

   printf("UDPThreadPara3: %s, len %d\n", (char*)UDPThreadPara3.pData, UDPThreadPara3.len);
   
   return 0;
}

3.不指定型別名直接定義結構體型別變數:

一般形式為:
struct
{
成員表列
}變數名錶列;

struct
{
	void *pData;
	int Len;
}UDPThreadPara1,UDPThreadPara2;
  • 1
  • 2
  • 3
  • 4
  • 5

這種方式只能夠定義一次,不能再以此定義其它變數。

一個在該定義方式下的程式例子:

#include<stdio.h>

struct
{
    void *pData;
    int len;
}UDPThreadPara1,UDPThreadPara2;

int main()
{
   UDPThreadPara1.pData = "hello";
   UDPThreadPara1.len = 1;

   UDPThreadPara2.pData = "world";
   UDPThreadPara2.len = 2;

   printf("UDPThreadPara1: %s, len %d\n", (char*)UDPThreadPara1.pData, UDPThreadPara1.len);

   printf("UDPThreadPara2: %s, len %d\n", (char*)UDPThreadPara2.pData, UDPThreadPara2.len);

   return 0;
}

 

相關文章