如何在循环中更改字段



我试图为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指针),所以实现

应该不会太难。像这样:

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

现在指针start + offset将指向当前字段。注意,上面的代码期望所有字段都是char*。如果你想添加更多类型,那么循环应该使用void*并跳过广告

最新更新