【发布时间】:2014-02-01 23:38:54
【问题描述】:
我有一些关于反转以空结尾的 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 */
}
}
}
【问题讨论】:
-
如果您确实传递了
"opal",那将是未定义的行为,因为您不允许修改字符串文字。 -
@ShafikYaghmour 那你会通过什么?
-
一个字符数组,
char arr[] = "opal";. -
要理解 C 指针,我永远不会将 char* 视为字符串,我会认为它只是一个内存地址。但在大多数情况下,char* 指针将指向包含以 NULL 结尾的字符串的内存地址。
-
测试
if (str) {不提供安全性。如果str是NULL,那么end是NULL and the next LOC is--end` --> 段错误。最好if (str == NULL) return;
标签: c pointers reverse dereference