How to create a new char* in standard C

soulblazer picture soulblazer · Jun 17, 2014 · Viewed 14.4k times · Source

I have this code made for C++ (it works):

char* ConcatCharToCharArray(char *Str, char Chr)
{
    char *StrResult = new char[strlen(Str) + 2]; 
    strcpy(StrResult, Str);
    StrResult[strlen(Str)] = Chr;
    StrResult[strlen(Str) + 1] = '\0';
    return StrResult;
}

/* Example: String = "Hello worl"
Char = "d"
Final string = "Hello world" */

The little problem is that I'm making a standard C program in Ubuntu and I need this code. And "new" is NOT being recognized as a reserved word and there's even a red mark under it.

I tried: char *StrResult[strlen(Str) + 2], but it doesn't work because that way only admits constant values. I'm guessing "malloc" would be the standard C solution in here, how could I do this with "malloc" or any other way for that matter? Thank you so much.

Answer

Graeme Perrow picture Graeme Perrow · Jun 17, 2014

new is the C++ way of allocating memory. In C you're right, you need to use malloc.

char* ConcatCharToCharArray(char *Str, char Chr)
{
    size_t len = strlen( Str );
    char *StrResult = malloc( len + 2 );
    /* Check for StrResult==NULL here */
    strcpy(StrResult, Str);
    StrResult[len] = Chr;
    StrResult[len+1] = '\0';
    return StrResult;
}

When you're done with the memory, you'd call free( StrResult ).