【发布时间】:2014-06-19 03:56:31
【问题描述】:
我想编写一个函数,如果它在结构中找到保存在作者姓名中的子字符串,则删除结构列表的条目。问题是, strstr() 似乎没有找到任何匹配项。我不想知道我是在正确删除条目还是以正确的方式移动列表指针(想自己弄清楚)。
void z(LIBRARY *first){
int i = 0, j = 0 ;
LIBRARY *nextZ = first->next , *prevZ = first;
char *name = (char*) malloc (102*sizeof(char)), *name2 = (char*) malloc (102*sizeof(char)), c ;
getchar();
fgets(name, 102, stdin); // Function gets the string the user is looking for.
while (name[j]!= '\0'){
name[j]= toupper(name[j]); // Converts it to upper case to ignore case types.
j++;
}
j=0;
printf("%s", name);
while ( nextZ ){ // Function starts going through the list of structures
name2 = nextZ->authors; //Function gets string saved in current structure->authors
while (name2[j]!= '\0'){
name2[j]= toupper(name2[j]);
j++;
}
j = 0;
printf("%s", name2);
if ( (strstr( name2, name))!=NULL ){
/*This is where the problem is. It seems like
the function never finds a substring in the structure->authors entry.*/
i++;
prevZ->next = nextZ->next;
nextZ = nextZ->next->next;
}
else {
prevZ = prevZ->next;
nextZ = nextZ->next;
}
}
printf("Vymazalo sa %d zaznamov\n", i); //Prints out how many entries of the list got deleted.
}
【问题讨论】:
-
1.要了解
strstr()是如何工作的,请编写一个简单的 main,它除了玩strstr()之外什么都不做。 2. 使用调试器检查每一步的所有相关变量,以了解您的程序真正执行的操作。 -
顺便说一句:代码在这里引入了很大的内存泄漏:
name2 = nextZ->authors; -
想法:把这个
printf("%s", name2);改成printf("name2='%s', name='%s'\n", name2, name); -
嘿,谢谢,我发现了主要问题-我将行尾字符加载到名称中,因此找不到该字符串。但是 name2 = nextZ->authors; 中的大内存泄漏是什么意思? ?
-
看看你给指针
name2分配了什么。