为什么我的removeWhitespace功能不起作用?

时间:2012-11-02 04:36:32

标签: c

我在包含以下内容的行中收到了段错误错误:

*pointer++ = *pointer_2++

不确定原因。

String声明为(在我的主要内部):

char *str = "Why doesn't this function work?"

这是我的职责:

void removewhitespace(char *str)
{
        // remove whitespace from the string.                                   
  char *pointer = str;
  char *pointer_2 = str;
 do{

    while (*pointer_2 == ' ' || *pointer_2 == '\n' || *pointer_2 == '\t')
      pointer_2++;

  }while (*pointer++ = *pointer_2++);

}

3 个答案:

答案 0 :(得分:6)

这是因为你的函数修改了字符串,你传递的是字符串文字的地址;修改字符串文字是未定义的行为。

更改此

char *str = "Why doesn't this function work?";

到这个

char str[] = "Why doesn't this function work?";

,您的功能将按预期工作。

答案 1 :(得分:0)

char *pointer = str;

此分配不是必需的,因为这是目标指针。你的'pointer_2'指向实际的字符串。所以你可以使用like,

char *指针;

char * pointer_2 = str;

答案 2 :(得分:0)

你的* str的地址被指针改变了 所以* p保存地址,数组保持值