Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ - How to append a char to char*?

Tags:

c++

char

append

I've tried so may ways on the Internet to append a character to a char* but none of them seems to work. Here is one of my incomplete solution:

char* appendCharToCharArray(char * array, char a)
{
    char* ret = "";
    if (array!="") 
    {
        char * ret = new char[strlen(array) + 1 + 1]; // + 1 char + 1 for null;
        strcpy(ret,array);
    }
    else
    {
        ret = new char[2];
        strcpy(ret,array);
    }

    ret[strlen(array)] = a;  // (1)
    ret[strlen(array)+1] = '\0';
    return ret;
}

This only works when the passed array is "" (blank inside). Otherwise it doesn't help (and got an error at (1)). Could you guys please help me with this ? Thanks so much in advanced !

like image 532
sonlexqt Avatar asked Nov 10 '13 16:11

sonlexqt


People also ask

How do I add a character to a char array?

append(char[] str) method appends the string representation of the char array argument to this sequence. The characters of the array argument are appended, in order, to the contents of this sequence. The length of this sequence increases by the length of the argument.

Can you append a char to a string?

Use the strncat() function to append the character ch at the end of str. strncat() is a predefined function used for string handling. string.

How do I add a character to a string pointer?

The simplest solution, lacking any context, is to do: char buffer[ strlen(line) + 1 ]; strcpy(buffer, line); You may be used to using pointers for everything in Java (since non-primitive types in Java are actually more like shared pointers than anything else).


1 Answers

Remove those char * ret declarations inside if blocks which hide outer ret. Therefor you have memory leak and on the other hand un-allocated memory for ret.

To compare a c-style string you should use strcmp(array,"") not array!="". Your final code should looks like below:

char* appendCharToCharArray(char* array, char a)
{
    size_t len = strlen(array);

    char* ret = new char[len+2];

    strcpy(ret, array);    
    ret[len] = a;
    ret[len+1] = '\0';

    return ret;
}

Note that, you must handle the allocated memory of returned ret somewhere by delete[] it.

 

Why you don't use std::string? it has .append method to append a character at the end of a string:

std::string str;

str.append('x');
// or
str += x;
like image 104
masoud Avatar answered Oct 21 '22 14:10

masoud