Take the 2-minute tour ×

How do I remove chars from the end of a char*? I have: "123456ABC" and I want: "123456". Thanks!

share|improve this question
What have you tried? –  Seth Carnegie Oct 9 '12 at 1:15
Char? Char pointer? Char array? Char pointer array? Hmmm. –  Kerrek SB Oct 9 '12 at 1:18

3 Answers 3

You could set one of the elements to the null character. Say you wanted to cut a string "123456ABC" down to "123456", you could just do,

str[6] = '\0';

BUT the rest of the string will still have memory allocated for it. What you probably want to do is make a new string and copy the desired portion of your old string over to it, and then delete the old string.

share|improve this answer
I'd like to point out that this will not work if str is a pointer to a string literal. –  Kludas Oct 9 '12 at 3:27

Terminate char * string with '\0'.

char c[] = "123456ABC";
c[6] = '\0';
share|improve this answer
Thanks! Solved! ;-) –  Kimberlee Graham-Knight Oct 9 '12 at 1:21

If you have the length of the desired remaining string, length, set str[length]='\0' and do:

// Assuming str was obtained through malloc/realloc functions.
str = realloc(str, sizeof(char)*(1+length));

This way you shorten the conceptual string and also the memory it uses, in case you want to optimise!

Edit: thanks to Jim Balter for raising issues with my original proposal!

share|improve this answer
You're assuming str was obtained from malloc (or realloc). Also, sizeof(char) is mandated to be == 1 and is not necessary. And you changed the meaning of length from length of string to amount allocated. –  Jim Balter Oct 9 '12 at 1:50
I'll give you the first one! While sizeof(char) is mandated, I believe from seeing other people's learning curves that this verbosity helps clarify concepts, but I see your point. And I called length in this case the amount of chars that the string would have after reduction... –  mcoimbra Oct 9 '12 at 2:11
after the realloc, str[length]='\0' is UB. And I prefer the more general realloc(array, nelems * sizeof *array), which is independent of the type. –  Jim Balter Oct 9 '12 at 2:12
UB? Pardon my ignorance but what does that mean? –  mcoimbra Oct 9 '12 at 2:13
Undefined behavior. Again: you changed the meaning of length from the length of the string to the length of the array. Better would be str = realloc(str, length+1);. –  Jim Balter Oct 9 '12 at 2:14

Your Answer


