我有一些关于反转以空字符结尾的C字符串的概念性问题,以及关于指针性质的澄清问题。
输入可能是
char arr[] = "opal";
代码如下:
void reverse(char *str) { /* does *str = opal or does *str = o since the pointer str is type char? */
char* end = str; /* what is the difference between char* end and char *end? and is *end pointing to opal now? */
char tmp;
if (str) { /* if str isn't null? */
while (*end)
++end;
}
--end; /* end pointer points to l now */
while (str < end) { /* why not *str < *end? is this asking while o < l? */
tmp = *str; /* tmp = o */
*str++ = *end; /* what is the difference between *str++ and ++str? does *str++ = l? */
*end-- = tmp; /* *end points to o */
}
}
}
char arr[] = "opal";
. - Shafik Yaghmourif (str) {
没有提供安全性。如果str
是NULL
,那么end
也是NULL
,下一个 LOC 是--end
--> seg fault。最好的方法是if (str == NULL) return;
。 - chux - Reinstate Monica