簡體   English   中英

如何在循環中更改字段

[英]how to change field in a loop

我試圖為 3 個不同的字段分配內存,每次我需要檢查 malloc 是否失敗。 是否可以使用循環使其更清潔?

    newContact->firstName = malloc(((int)strlen(newFirstName) + 1) * sizeof(char));
    if (newContact->firstName == NULL) {
        printf("The addition of the contact has failed!");
        //free
        exit(1);
    }
    newContact->lastName = malloc(((int)strlen(newLastName) + 1) * sizeof(char));
    if (newContact->lastName == NULL) {
        printf("The addition of the contact has failed!");
        //free
        exit(1);
    }
    newContact->phoneNum = malloc(((int)strlen(newPhoneNum) + 1) * sizeof(char));
    if (newContact->phoneNum == NULL) {
        printf("The addition of the contact has failed!");
        //free
        exit(1);
    }

我知道我可以創建一個接受指針並檢查其內部的函數,但是如果我需要分配給 10 個字段會怎樣? 50個字段? 我想遍歷所有字段或某些部分,如果可能的話,在循環中分配和檢查失敗。

只要您知道結構的每個元素的大小,您就可以通過原始內存地址進行迭代並每次跳過 sizeof(field) 字節的內存。 看起來所有的字段都是字符串(字符指針),所以實現起來應該不會太難

像這樣:

char* start = ...;
for (char* offset = 0; offset < numberOfFields; offset++)

現在指針 start + offset 將指向當前字段。 請注意,上面的代碼期望所有字段都是 char*。 如果要添加更多類型,則應調整循環以使用 void* 並跳過廣告

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM