c语言 - 我试图在K&R练习中定义字符串结束函数



我试图定义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++会发生什么:

  1. s++被计算 - 这首先存储s的当前值(我们称之为s0(,然后递增s
  2. s0被取消引用

这与

char *s0 = s;
s += 1;
char c = *s0;

*++s会发生什么:

  1. s递增
  2. s被取消引用

这与

s += 1;
char c = *s;

希望这是有道理的。

最新更新