【发布时间】:2017-05-16 14:02:37
【问题描述】:
这是我正在尝试做的,但我的代码要么没有编译,要么给我一个意外的输出“BC”而不是“B”。
#include <stdio.h>
void removeFirstAndLastChar(char** string) {
*string += 1; // Removes the first character
int i = 0;
for (; *string[i] != '\0'; i++);
*string[i - 1] = '\0';
}
int main(void) {
char* title = "ABC";
removeFirstAndLastChar(&title);
printf("%s", title);
// Expected output: B
return 0;
}
我在这里查看了很多与通过引用传递指针有关的答案,但似乎没有一个包含我想在 removeFirstAndLastChar() 函数中执行的操作。
【问题讨论】:
-
尝试修改字符串文字的未定义行为。
-
你应该把
char* title = "ABC";改成char title[] = "ABC"; -
你需要
(*string)[i]而不是*string[i]。 -
@Nidhoegger 使用指向文字的指针根本不正确,因为函数会修改它。
标签: c pointers pass-by-reference