#include <stdio.h>
int strend(char *s, char *t);
int main()
{
char a[] = "hello world";
char b[] = "orld";
int i = strend(a,b);
printf("%d",i);
return 0;
}
/* Write the function strend(s,t), which returns 1 if the string t occurs at the end of the string s, and zero otherwise. */
int strend(char *s, char *t)
{
char *se = s;
char *te = t;
while (*se)
se++;
while (*te)
te++;
while(se>=s&&te>=t){
if (*se!=*te)
return 0;
se--;te--;// is this alright???
}
return ++te==t;
}
这样指针走在数组指针之前,是否存在数组指针初始化为0而导致下溢问题的情况?在这种情况下我应该如何重写代码?
我觉得一切都很好。除了该函数不检查 NULL 输入之外,这可以定义为未定义的行为,这很好。
a 和 b 不能为零。只有当您通过 malloc() 动态分配堆内存时才会发生这种情况,当然您应该始终检查 malloc 是否失败并优雅地处理它。
指针 se 和 te 的地址当然可能指向不是程序内存的东西,但只要您不取消引用(尝试读取或写入指向的地址)就不会出错。 比较他们的价值观总是没有问题的。