Trying to remove the last character in a char array in C
14,475
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:";
Author by
letter Q
Updated on July 30, 2022Comments
-
letter Q almost 2 years
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);
-
Admin over 10 years@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 *
.