一、C 結構體數組指針
C 結構體數組可以使用指針進行操作。通過指向結構體數組的指針,可以遍曆數組中的所有元素。聲明指向結構體數組的指針,語法如下:
struct Person {
char name[20];
int age;
};
struct Person p[10];
struct Person *pPtr = p;
對於上述代碼,pPtr 是指針變量,指向結構體數組 p 的第一個元素。
通過 (*pPtr).name 和 pPtr->name 可以訪問數組中的成員。
二、C 結構體數組傳遞
可以將結構體數組作為參數傳遞給函數,語法如下:
void printPeople(struct Person people[], int length) {
for (int i = 0; i < length; i++) {
cout << people[i].name << " is " << people[i].age << " years old" << endl;
}
}
在調用此函數時,可以傳遞結構體數組及其長度:
struct Person p[3] = {{"Tom", 25}, {"Jerry", 24}, {"Mickey", 26}};
printPeople(p, 3);
三、C 結構體數組賦值
可以使用等號將一個結構體數組的所有元素值賦給另一個結構體數組:
struct Person p1[2] = {{"Tom", 25}, {"Jerry", 24}};
struct Person p2[2];
p2 = p1; // 報錯
但是上面的代碼是錯誤的,不能直接使用等號將結構體數組賦值給另一個結構體數組。可以使用循環遍歷來完成賦值操作:
for (int i = 0; i < 2; i++) {
p2[i] = p1[i];
}
四、結構體數組
結構體數組是指由結構體構成的數組。結構體數組的訪問方式與普通數組類似。
struct Point {
int x;
int y;
};
struct Point p[3] = {{0, 0}, {1, 1}, {2, 2}};
cout << p[0].x << "," << p[0].y << endl; // 輸出 0,0
五、C 結構體數組全部初始化為0
可以使用下列方式將結構體數組全部初始化為0:
struct Person p[10] = {0};
這樣會將所有成員變量全部置為0。
六、C 結構體數組不能用const
C 結構體數組不能用 const 修飾。
struct Person {
char name[20];
int age;
};
const struct Person p[2] = {{"Tom", 25}, {"Jerry", 24}}; // 報錯
七、C 結構體數組刪除
結構體數組不支持刪除元素的操作。可以使用標記位來實現邏輯上的刪除。也可以使用動態數組替代結構體數組,以便進行增刪操作。
八、C 結構體數組初始化
結構體數組初始化時可以使用類似普通數組的方式:
struct Coordinate {
double x;
double y;
};
struct Coordinate point[3] = {{1.0, 2.0}, {2.5, 6.3}, {5.2, 1.8}};
也可以在定義結構體時進行初始化:
struct Coordinate {
double x;
double y;
} point[3] = {{1.0, 2.0}, {2.5, 6.3}, {5.2, 1.8}};
九、C 結構體數組
C 結構體數組是一種常見的數據結構。
struct Student {
char name[20];
int age;
float grade;
};
struct Student stu[3] = {{"Tom", 18, 85.5}, {"Jerry", 19, 92.0}, {"Mickey", 20, 88.5}};
通過遍歷結構體數組,可以對每個元素進行處理,完成各種計算、排序、查找等操作。
十、結構體數組怎麼使用
結構體數組是C++中常用的數據結構之一,可以用來存儲各種信息。
要使用結構體數組,需要:
- 定義一個結構體類型
- 創建一個結構體數組
- 初始化數組中的每個元素
- 遍曆數組,對每個元素進行處理
下面是一個示例代碼,用於演示結構體數組的使用方法:
struct Employee {
char name[20];
int age;
float salary;
} emp[3] = {{"Tom", 25, 8000.0}, {"Jerry", 30, 10000.0}, {"Mickey", 35, 12000.0}};
int main() {
for (int i = 0; i < 3; i++) {
cout << emp[i].name << " is " << emp[i].age << " years old and earns " << emp[i].salary << " yuan per month" << endl;
}
return 0;
}
運行上述代碼,將輸出三個員工的名字、年齡和工資。
原創文章,作者:TMTF,如若轉載,請註明出處:https://www.506064.com/zh-hant/n/134303.html