Hi guys, I would like to add a char to the end of a char*

So imagine the following:

char* test = "ABC"

I want to add D to the end of it to get

test == "ABCD"

for the sake of argument, I can not use strcat as I have to pass D as a char not a string ('D' not "D")

As this is proving to be rather difficult I was hoping you fine people could help me.

I saw a nice idea on here where someone produced a method like below:

char* appendChar(char* originalString, char toAppend)
{
   char* complete = (originalString with toAppend appendended to the end)
   return complete;
};

Obviously I'm missing a big chunk out of there but you get the idea. The problem with the method was that it was written for C++ and wouldn't work for me in C.

Let's brainstorm then, how would you guys do this?

Firstly

char* test = "ABC"

creates a read only c-string so you can't modify it...

You want something like

char test[10] = {'A','B','C','\0'};

Edited 6 Years Ago by gerard4143: n/a

ooo, didn't know that, no problem,

still, can we make a method (function?) that'll return a whole new char* with the char appended to the end of it?

you see, the device I've built and i'm programming on has lots of prewritten methods which i'm not going to recode, don't want to risk it, not that clever XD

Problem is, one of the part of it outputs a String and I need to pass it to another part which takes char* so this is all part of that problem.

but never mind all that, important thing is that i have to end up with a char* at the end to work with :)

Here's a solution but it assumes a few things
1. Your passing a c-string...I use strlen() which requires a c-string
2. The c-string passed has room for the extra character.

#include <stdio.h>
#include <string.h>

char* append_it(char *cptr, const char c)
{
	int len = strlen(cptr);
	cptr[len + 1] = cptr[len];
	cptr[len] = c;

	return cptr;
}

int main()
{
	char test[10] = {'A','B','C','\0'};

	fprintf(stdout, "new c-string->%s\n", append_it(test, 'D'));
	fprintf(stdout, "new c-string->%s\n", append_it(test, 'E'));
	return 0;
}

Edited 6 Years Ago by gerard4143: n/a

oh looks good, i shall try it tomorrow morning and let you know how i do, thanks for your help so far.

This article has been dead for over six months. Start a new discussion instead.