我试图定义strend(s,t)
函数,如果字符串 t 在 s 字符串的末尾返回1,否则返回零,这是我的代码。
typedef enum state
{
Not_occured ,
occured
}State;
char a[]="Hello world zone";
char b[]="ne";
int main(void)
{
int x = 0 ;
x = strend(a,b);
printf("%d",x);
return 0;
}
int strend(char *s, char *t)
{
while(*++s);
while(*++t);
while(*t-- == *s--)
if(!(*t))
return occured;
return Not_occured;
}
修改后的代码
int strend(char *s, char *t)
{
char *ptr = s;
while(*++s);
while(*++t);
while(*t-- == *s--)
if(s == ptr)
return occured;
return Not_occured;
}
为什么前缀在这里工作while(*++s);
,while(*++t);
和后缀不起作用?
if(!(*t))
假定字符串中的第一个字符之前有一个 NUL 字符。这不仅是一个不正确的假设,而且还试图访问数组边界之外的内存。
另外,while(*t-- == *s--)
...当 2 个字符串相同或t
长度超过s
时会发生什么?
这是一个简单的解决方案:
int strend(char *s, char *t) {
if (s == NULL || t == NULL) return Not_occured;
size_t s_len = strlen(s);
size_t t_len = strlen(t);
if (t_len <= s_len) {
return 0 == strcmp(&s[s_len - t_len], t) ? occured : Not_occured;
}
return Not_occured;
}
由于现在更清楚原始问题是关于修复前和修复后操作,因此我已经更新了。
首先,了解两者之间的区别:
int x = 1;
printf("%d", x++);
// Prints 1 because x is evaluated before the inc
x = 1;
printf("%d", ++x);
// Prints 2 because x is evaluated after the inc
现在,一些运算符优先级:
postfix > dereference
prefix == dereference, right-to-left assoc.
*s++
会发生什么:
s++
被计算 - 这首先存储s
的当前值(我们称之为s0
(,然后递增s
s0
被取消引用
这与
:char *s0 = s;
s += 1;
char c = *s0;
*++s
会发生什么:
s
递增s
被取消引用
这与
:s += 1;
char c = *s;
希望这是有道理的。