查找字符串结尾:*s++ VS *s 然后 s++
我正在编写一个简单的字符串连接程序。
该程序按照我发布的方式运行。但是,我首先使用以下代码编写它来查找字符串的结尾:
while (*s++)
;
但是,该方法不起作用。我传递给它的字符串没有正确复制。具体来说,我尝试将“abc”复制到保存“\0”的 char[] 变量。
从阅读 C K&R 的书来看,它看起来应该可行。该紧凑形式应采取以下步骤。
- *s 与 '\0' 进行比较
- s 指向下一个地址
那么为什么它不起作用呢?我在 Debian 上使用 gcc 进行编译。
我发现这个版本确实有效:
strncat(char *s, const char *t, int n)
{
char *s_start = s;
while (*s)
s++;
for ( ; n > 0 && *t; n--, s++, t++)
*s = *t;
*(s++) = '\0';
return s_start;
}
提前致谢。
I'm writing a simple string concatenation program.
The program works the way I have posted it. However, I first wrote it using the following code to find the end of the string:
while (*s++)
;
However, that method didn't work. The strings I passed to it weren't copied correctly. Specifically, I tried to copy "abc" to a char[] variable that held "\0".
From reading the C K&R book, it looks like it should work. That compact form should take the following steps.
- *s is compared with '\0'
- s points to the next address
So why doesn't it work? I am compiling with gcc on Debian.
I found that this version does work:
strncat(char *s, const char *t, int n)
{
char *s_start = s;
while (*s)
s++;
for ( ; n > 0 && *t; n--, s++, t++)
*s = *t;
*(s++) = '\0';
return s_start;
}
Thanks in advance.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
在
while (*s++);
结束后,s
指向空终止符后面的字符。在下面的代码中考虑到这一点。After the end of
while (*s++);
,s
points to the character after the null terminator. Take that into account in the code that follows.问题是
,即使 s 为零(*s 为 false),“始终递增 s”也
只会在 *s 非零时递增 s
,因此第一个将让 s 指向第一个 \0 之后的第一个字符 ,而第二个将使 s 指向第一个 \0。
The problem is that
Always Increments s, even when s is zero (*s is false)
only increments s when *s is nonzero
so the first one will leave s pointing to first character after the first \0, while the second one will leave s pointing to the first \0.
有差别。在第一种情况下,s 将指向 '\0' 之后的位置,而第二种情况则停在 '\0' 处。
There is difference. In the first case, s will point to the position after '\0', while the second stops right at '\0'.
正如 John Knoeller 所说,在运行结束时,它将指向 NULL 之后的位置。 但是没有必要为了正确的解决方案而牺牲性能。自己看看:
while (*s++); --s;
应该可以解决问题。
As John Knoeller said, at the end of the run it'll s will point to the location after the NULL. BUT There is no need to sacrifice performance for the correct solution.. Take a look for yourself:
while (*s++); --s;
Should do the trick.
另外,请注意,在 C 中,指针指向未分配的内存在技术上是非法的,即使您不取消引用它。所以一定要修复你的程序,即使它看起来可以工作。
In addition what has been said, note that in C it is technically illegal for a pointer to point to unallocated memory, even if you don't dereference it. So be sure to fix your program, even if it appears to work.