我通过指针编写了一个字符串反转函数,代码运行正常,没有错误,但有一些我想知道的事情。
这是我的代码:
char * xstrrev(char *s1, char *s2){
register char *p = s1;
register char *q = s2;
char *r = s2;
do{
*(s2++) = *(p++); //first copy the string, afterwards, replace it
}while(*p);
p--; //to eliminate trailing '\0' while reversing.
do {
*(q++) = *(p--); //replace contents by reverse contents,
}while(*q);
return r;
}
此处,在第三行的最后一行中,* q必须具有值'\0'
,因为我们先前复制了确切的字符串,因此,'\0'
必须已被复制。
然而,当我替换我的
*(s2 ++)= *(p ++);
带
的p ++;
,即我只将p
增加到字符串的结尾,并且不要将字符串复制到s2
,条件
而(* q)的
仍然有效。在这种情况下,*q
不应该有\0
,对吧?那么这个条件如何运作呢?
当我用while(*q)
while(*q!='\0')
时,它是一样的
编辑::它被称为:
char a[110]= "hello";
char f[116];
xstrrev(a,f); //reverse a and put to f
puts(f);
答案 0 :(得分:3)
如果它正常工作,那完全是偶然的。调用者提供的字符串s2
可能在\0
结尾处有s2
。但你不能依赖于此,它取决于调用者如何初始化它传递的字符串。
另一种可能性是,a
之前的内存恰好包含\0
。如果你有类似的话,就会发生这种情况:
char something[] = "foo";
char a[110] = "nacan";
something
的内存正好位于a
的内存之前,因此something
的尾随空值将位于a
的第一个字节之前。
在这种情况下会发生的情况是,循环会复制此\0', but it doesn't stop immediately. It keeps on copying until it eventually runs in to a
\ 0 in
* q . But when you look at
f , you just see the reverse of
a`,因为此空字节已被复制。
如果您希望看到这种情况发生,请在调试器中单步执行您的功能。
C语言无法保证这一点,而是经常进行内存布局。