I am trying to concatenate a char to the end of a char*. I have a char* result that i want to add a character to the end of it. I'm not sure if I can do this with strcat.
you can just add it in, but if the array that char * points too isn't large enough, then you'll have to declare a new one... what code do you currently have?
- edit: when I say add it in, I mean, find where on the array to put it and put it there
Won't memset write the value 0 over 256 random bytes of memory there, since result is a pointer that has never been set to point at allocated memory? I'd expect to see a segfault there, if you're lucky, and if you're unlucky you'll trash something and not notice.
Also, strcat takes two char* parameters as input, not a char* and a char.
I used to have result as a char array, but changed it to a pointer. I guess ignore that for now.
My main issue is that I want to concatenate a char to a char*. How would i achieve that?
That's because you never set the value of result to any memory you have allocated. You are writing over the top of random memory.
You need to allocate yourself some memory, and then set the value of result to be equal to the address of the start of the allocated memory.
You could allocate the memory like this:
char someAllocatedMemory[300];
which would give you space for 300 char values, or like this
char* p1 = newchar[300];
which would also give you space for 300 char values; if you chose the second option, you would have to remember to deletewhen you are done with it.
Then, either replace result in your code with a pointer that has the value of the address of the start of the memory you allocated (in my example code, the value of p1 is the value of the address of the start of the allocated memory), or set the value of result to the address of the start of your allocated memory.
I maintain that all that junk I said about how result pointed to unallocated memory was true, but yes, I completely missed that it would all break at strcat :( ne555 is bang on the money. Listen to him :)
you probably should take things out of global scope ... plus if you want to use a pointer, then allocate and keep track of the size and what is used. You can use something to keep track and that would eliminate some headache for you and just append a null char at the end when done. Plus you can reallocate memory to the pointer if you need more since you are using them anyway.