首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

C++ 結構體清零與傳參方式示範

     編輯:程式設計綜合問答

結構體定義

typedef struct {
    char name[20];
    int math;
    int eng;
    int db;
} Student;

方法一:傳參考清零(推薦)

void SetZero(Student& s) {
    s.math = 0;
    s.eng = 0;
    s.db = 0;
    // name 可用 memset 或 strcpy
}

呼叫:SetZero(s); 直接修改原物件,效率高且語意清晰。

方法二:傳值回傳新物件(教學示範)

Student* SetZero1(Student s) {
    Student *p = (Student*)malloc(sizeof(Student));
    memcpy(p, &s, sizeof(Student));
    p->math = 0;
    p->eng = 0;
    p->db = 0;
    return p; // 呼叫端需 free
}

呼叫:s = *SetZero1(s); 需手動管理記憶體,易洩漏,僅供理解指標操作。

完整測試程式

#include <stdlib.h>
#include <stdio.h>
#include <string.h>

int main() {
    Student s;
    s.math = 100;
    printf("%d\n", s.math); // 100
    SetZero(s);
    printf("%d\n", s.math); // 0
    s.math = 100;
    printf("%d\n", s.math); // 100
    s = *SetZero1(s);
    printf("%d\n", s.math); // 0
    return 0;
}

最佳實務建議

  • 優先使用 傳參考 或 傳指標 修改結構體,避免大型結構體拷貝開銷。
  • C++ 建議將清零邏輯封裝為成員函式 void reset() 或建構子預設初始化。
  • 若需 C 相容,提供 void Student_init(Student* s) 與 void Student_reset(Student* s)。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved