2

So I wrote the following method:

void removeEndingColon(char *charArrayWithColon) {
    // remove ':' from variableName
    size_t indexOfNullTerminator = strlen(charArrayWithColon);
    charArrayWithColon[indexOfNullTerminator - 1] = '\0'; // replace ':' with '\0'
}

But when I test it with the following code in eclipse, I get no output and I don't know why my executable isn't able to run.

char *charArray1 = "ThisHasAColonAtTheEnd:";
removeEndingColon(charArray1);
letter Q
  • 14,735
  • 33
  • 79
  • 118
  • What do you mean by no output and what do you mean by not able to tun what is the exact error you get – mmmmmm Nov 18 '13 at 19:55
  • 1
    possible duplicate of [Why do I get a segmentation fault when writing to a string?](http://stackoverflow.com/questions/164194/why-do-i-get-a-segmentation-fault-when-writing-to-a-string) – n. m. could be an AI Nov 18 '13 at 19:57
  • It says my .exe file isn't able to run. – letter Q Nov 18 '13 at 19:57
  • 3
    Does it say just "your .exe isn't able to run" ? That's a very bad error message indeed. – n. m. could be an AI Nov 18 '13 at 20:01
  • Please describe the ***exact*** error message. It would help if you describe your platform, (Linux/Windows/Other?) and how you're running your program (Command line, debugger, other?) – abelenky Nov 18 '13 at 20:04

2 Answers2

5
char *charArray1 = "ThisHasAColonAtTheEnd:";` 

Here you point charArray1 to a string literal. In C, you cannot modify a literal. See e.g this question

You can store the string in an array which you can modify. So just do

char charArray1[] = "ThisHasAColonAtTheEnd:"; 
Community
  • 1
  • 1
nos
  • 223,662
  • 58
  • 417
  • 506
  • 3
    @QuinnLiu Next time **turn on compiler warnings and pay attention to them.** You should have gotten a warning when assigning a string literal to a non-const `char *`. –  Nov 18 '13 at 20:00
0

The problem here might be that your string is allocated in read only area so you cannot change it. Fist copy and edit a copy.

BTW. Depending on a compiler and execution environment it might actually work - on some embedded systems for example.

Artur
  • 7,038
  • 2
  • 25
  • 39