c語言中將結構體對象指針作為函數的參數實現對結構體成員的修改。
1、
#include <stdio.h> #define NAME_LEN 64 struct student{ char name[NAME_LEN]; int height; float weight; long schols; }; void hiroko(struct student *x) // 將struct student類型的結構體對象的指針作為函數的形參 { if((*x).height < 180) // x為結構體對象的指針,使用指針運算符*,可以訪問結構體對象實體,結合.句點運算符,可以訪問結構體成員,從而對結構體成員進行修改。 (*x).height = 180; if((*x).weight > 80) (*x).weight = 80; //因為傳入的是結構體對象的指針,因此可以實現對傳入的結構體對象的成員進行修改 } int main(void) { struct student sanaka = {"Sanaka", 173, 87.3, 80000}; hiroko(&sanaka); //函數的實參需要是指針,使用取址運算符&獲取對象sanaka的地址 printf("sanaka.name: %s\n", sanaka.name); printf("sanaka.height: %d\n", sanaka.height); printf("sanaka.weight: %.2f\n", sanaka.weight); printf("sanaka.schols: %ld\n", sanaka.schols); return 0; }
等價於以下程序(使用箭頭運算符 ->)
#include <stdio.h> #define NAME_LEN 64 struct student{ char name[NAME_LEN]; int height; float weight; long schols; }; void fun(struct student *x) // 函數的形參為指向struct student型的對象的指針 { if(x -> height < 180) // 指針 + ->(箭頭運算符)+ 結構體成員名稱 可以訪問結構體成員,從而實現結構體成員值的修改 x -> height = 180; if(x -> weight > 80) // 箭頭運算符 -> 應用於結構體對象指針,訪問結構體對象的結構體成員 x -> weight = 80; } int main(void) { struct student sanaka = {"Sanaka", 173, 87.3, 80000}; fun(&sanaka); // 函數的形參為struct student型的結構體對象指針, 因此使用取址運算符&傳入結構體對象sanaka的地址(指針), printf("sanaka.name: %s\n", sanaka.name); printf("sanaka.height: %d\n", sanaka.height); printf("sanaka.weight: %.2f\n", sanaka.weight); printf("sanaka.schols: %ld\n", sanaka.schols); return 0; }
箭頭運算符 只能應用於結構體對象的指針,訪問結構體對象的成員, 不能應用於一般的結構體對象。比如 sanaka -> height 會發生報錯。