基于K&R C练习5-4:字符串指针起始位设置与strend函数问题排查
问题描述
正在学习《K&R C语言程序设计》第二版,完成练习5-4时遇到问题。该练习要求编写strend函数,判断字符串t是否位于字符串s的末尾。
我的实现思路是先计算两个字符串的长度差,以此作为s中起始比较的位置,通过while循环逐字符比对,但运行时发现while (*p++ == *t++)中的指针p无法在字符串s中前移。
代码如下:
#include <stdio.h> #include <string.h> int strend(char *s, char *t) int main() { char s[] = "abcd"; char t[] = "cd"; printf("%d", strend(s,t)); } /* if the string t is founded in the end of string s, return 1, otherwise return 0*/ int strend(char *s, char *t) { int start; char *p; start = strlen(s) - strlen(t); /*get the length difference of two string*/ p = &s[start]; /*set the position of pointer p*/ while (*p++ == *t++) ; if (*t == '\0' && *p == '\0') return 1; else return 0; }
问题排查与修正
- 语法错误引发未定义行为:
int strend(char *s, char *t)这一行末尾缺少分号,编译器会将其与后续的int main()解析混淆,直接导致指针p的行为异常,这是核心问题。 - 循环结束后的判断逻辑错误:
while (*p++ == *t++)结束时,p和t都已指向匹配字符的下一位。此时只需判断t是否到达'\0'即可——只要t的所有字符都匹配完成,就说明t在s末尾,不需要同时要求*p == '\0'(比如s长度大于t但末尾匹配时,p不会指向s的结束符)。 - 边界情况未处理:如果
t的长度大于s,start会是负数,&s[start]会指向数组越界的位置,触发错误。
修正后的代码:
#include <stdio.h> #include <string.h> int strend(char *s, char *t); // 补充分号,修复语法错误 int main() { char s[] = "abcd"; char t[] = "cd"; printf("%d", strend(s, t)); } /* 判断字符串t是否位于s末尾,是则返回1,否则返回0 */ int strend(char *s, char *t) { int len_s = strlen(s); int len_t = strlen(t); // t比s长,直接返回0 if (len_t > len_s) return 0; char *p = s + len_s - len_t; // 定位到s中需要开始比对的位置 // 逐字符比对,直到不匹配或字符串结束 while (*p && *t && *p == *t) { p++; t++; } // t走到末尾说明所有字符匹配完成 return *t == '\0'; }
内容的提问来源于stack exchange,提问作者kim
相关产品推荐
相关产品推荐

