简体   繁体   English

如何在循环中更改字段

[英]how to change field in a loop

im trying to allocate memory for 3 different fields and every time i need to check if the malloc fails.我试图为 3 个不同的字段分配内存,每次我需要检查 malloc 是否失败。 is it possible to make it cleaner using a loop?是否可以使用循环使其更清洁?

    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);
    }

i know i can make a function that takes the pointer and checks inside of it, but what happens if i need to assign to 10 fields?我知道我可以创建一个接受指针并检查其内部的函数,但是如果我需要分配给 10 个字段会怎样? 50 fields? 50个字段? i want to go over all of the fields or certain parts of, and both assign and check for failure in a loop if possible.我想遍历所有字段或某些部分,如果可能的话,在循环中分配和检查失败。

As long as you know the size for each element of the struct, you could just iterate by raw memory addresses and skip sizeof(field) bytes of memory each time.只要您知道结构的每个元素的大小,您就可以通过原始内存地址进行迭代并每次跳过 sizeof(field) 字节的内存。 It seems that all of the fields are strings (char pointers), so it shouldn't be too difficult to implement看起来所有的字段都是字符串(字符指针),所以实现起来应该不会太难

Something like this:像这样:

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

Now the pointer start + offset would point at the current field.现在指针 start + offset 将指向当前字段。 Note that the code above expects all of the fields to be char*.请注意,上面的代码期望所有字段都是 char*。 If you want to add more types, then the loop should be adapted to use void* and to skip the ad如果要添加更多类型,则应调整循环以使用 void* 并跳过广告

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM