我有以下代码: (我只保留了我的问题的相关部分)
// Structure
struct first_list {
char firstname[100];
struct first_list * next;
};
struct last_list {
char lastname[100];
struct last_list * next;
};
void verify_name()
{
char firstname[100];
char lastname[100];
struct first_list * curr_first = loaded_first;
struct last_list * curr_last = loaded_last;
/////////// this part was added by me
while( curr_last != NULL )
{
strncpy(lastname, curr_last->lastname, sizeof( lastname ) - 1 );
valid = validate_name(sock,buffer,sizeof(buffer),firstname);
if(valid < 1)
fprintf(stderr, "%s is VALID\n", lastname);
else
fprintf(stderr, "%s is invalid\n", lastname);
curr_last = curr_last->next; //this is used for removing current record
}
printf( "LastName validation complete\n" );
break;
/////////// end of part added by me
while( curr_last != NULL && curr_first != NULL )
{
strncpy(firstname, curr_first->firstname, sizeof( firstname ) - 1 );
strncpy(lastname, curr_last->lastname, sizeof( lastname ) - 1 );
////////////////////////////////
//// irrelevant code (functions)
////////////////////////////////
if( curr_first->next == NULL && curr_last->next != NULL)
{
curr_last = curr_last->next;
curr_first = loaded_first;
}
else
curr_first = curr_first->next;
}
}
所以,我添加了一个新函数来验证函数之前的lastnames,它同时验证firstnames和lastnames(以优化整个过程)。问题是,如果我删除break命令,我会收到错误,因为验证后last_list为空。
如何只在结构中保留有效的姓氏,因为现在当移动到下一条记录时它正在删除当前的一条直到循环完成(NULL)??
答案 0 :(得分:1)
您在第一个循环中需要做的是:
struct last_list * prev = NULL;
struct last_list * next = NULL;
while (curr_last != NULL)
{
next = curr_last->next;
strncpy(lastname, curr_last->lastname, sizeof(lastname) - 1);
lastname[sizeof(lastname) - 1] = 0;
valid = validate_name(sock,buffer,sizeof(buffer),firstname);
if(valid < 1)
{
fprintf(stderr, "%s is VALID\n", lastname);
prev = curr_last;
}
else
{
fprintf(stderr, "%s is invalid\n", lastname);
if (prev == NULL)
loaded_last = curr_last->next; //this is used for removing when current is first record
else
prev->next = curr_last->next; //this is used for removing current record from mid-list
free(curr_last); //Freeing should be needed but depends on how you built your list.
}
curr_last = next;
}
curr_last = loaded_last;
这会从列表中删除您的curr_last
元素,并仅在其中保留有效的姓氏。
答案 1 :(得分:0)
你已经在循环中使用(例如)cur_last-&gt;“消耗”了列表,因此你需要重新初始化cur_first和cur_last指向列表的开头或者有一个执行这两个函数的循环