永远不会达到其他条款
我似乎在编写字符串搜索功能时遇到问题. strlength和strmid都是以前编写的功能,已经过测试并且正在工作.
int strfind(char * string1,char * string2) { /* if string1 contains the substring string2 returns the starting position of string2 in string1 otherwise returns -1 e.g. strinc("hello world","wor") returns 6 strinc("hello world","war") returns -1 */ int begPos = 0,endPos,count = 0,match = 1; char *tempStr; endPos = strlength(string2)-1; while (endPos <= strlength(string1)-1) { strmid(string1,begPos,tempStr); while (match == 1) { if (tempStr[count] == string2[count]) { if (count < strlength(string2)) count++; else break; } else match = 0; } if ( match == 1 ) return begPos; else { begPos++; endPos++; } } return -1; } 算法应该是这样的 >获取begPos和endPos之间的字符串段 我遇到的问题是 while (match == 1) { if (tempStr[count] == string2[count]) { if (count < strlength(string2)) count++; else break; } else match = 0; } 似乎永远不会达到else条款.返回的值似乎总是begPos初始化的值.这是一个家庭作业,但我已经使用不同的方法重写了几次,例如for循环,并做了多次干运行,似乎无法解决问题.任何你可以流下的灯都会非常感激. 干杯, espSquall strmid功能 void strmid(char * string1,int start,int end,char * string2) { /* copies the elements of string1 from start to end to string2 */ int len,count2 = 0; for (len = start; len <= end; len++) { string2[count2] = string1[len]; count2++; } string2[count2] = ' '; } 解决方法
我只有一点要提出来.
您认为tempStr如何设置为有用的东西? 行char * tempStr;将它设置为当时在堆栈上发生的任何事情,而C,缺少“正确”的引用传递,不能通过调用更改它: strmid(string1,tempStr); 要更改指针,您必须传入& tempStr而不是tempStr. 所以,在我看来,你的tempStr并没有指向任何可用的东西. 而且,根据你添加的strmid函数,这个程序肯定是在“未定义的行为”类中.快速修复,虽然kludgy,将改变: char *tempStr; 至: char tempStr[1000]; 这可能无法解决您的所有问题(并且它会引入缓冲区溢出的可能性),但它至少会为您提供一个定义良好的程序. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |