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);
Wang-Zhao-Liu Q
  • 13,555
  • 29
  • 73
  • 112

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
  • 215,098
  • 54
  • 400
  • 488
  • 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
  • 6,790
  • 2
  • 24
  • 37