简体   繁体   English

在C内存故障中从字符串中删除空格

[英]Removing spaces from a string in C Memory fault

I'm writing a simple code for removing spaces from a string in C however I get the following message after compiling: EXC_BAD_ACCESS (code=2, adresss=....). 我正在编写一个简单的代码以从C中的字符串中删除空格,但是编译后得到以下消息:EXC_BAD_ACCESS(代码= 2,地址= ....)。 It's coming from the line '*temp = *str' however I don't understand why? 它来自“ * temp = * str”行,但是我不明白为什么? How can I fix it? 我该如何解决?

void removeSpaces(char * str)
{
  char * temp = str;

  while (*str != '\0') {
    if (*str != ' ') {
      *temp = *str;
      temp++;
     }
    str++;
  }
  *temp = '\0';
}

The function works fine when passed a string declared like this 传递这样声明的字符串时,该函数可以正常工作

char s[] = "Hallo  World!";

but if you declared the string like this, as a pointer to string literal 但是如果您这样声明字符串,则作为指向字符串文字的指针

char *s = "Hallo  World!";

you are not supposed to modify the string. 您不应该修改字符串。

It seems that you are passing an string literal. 似乎您正在传递字符串文字。 temp and str pointing to same string literal. tempstr指向相同的字符串文字。 With statement *temp = *str; 用语句*temp = *str; you are modifying the that literal which should not be modified. 您正在修改不应修改的文字。

To fix the problem allocate memory for temp 要解决此问题,请为temp内存分配

char *temp = malloc(strlen(str) + 1);   

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM