Trying to remove the last character in a char array in C

Wang-Zhao-Liu Q picture Wang-Zhao-Liu Q · Nov 18, 2013 · Viewed 14.3k times · Source

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);

Answer

nos picture nos · Nov 18, 2013
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:";