Home > OS >  how to change field in a loop
how to change field in a loop

Time:12-23

im trying to allocate memory for 3 different fields and every time i need to check if the malloc fails. 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? 50 fields? 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.

CodePudding user response:

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. 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. Note that the code above expects all of the fields to be char*. If you want to add more types, then the loop should be adapted to use void* and to skip the ad

  • Related