Search code examples
ccharstring-literals

Adding a char to a string literal with C


I have defined a string literal as

char *name

and I want to add a char to name (the char is defined as char d = 'a').

I have tried

strcpy(name, d);

but when I try to print it I get a seg fault. How could I do this?


Solution

  • Use name[strlen(name)] = d.

    char *name = malloc(80);
    // some code that puts something in *name
    strcpy(name, "Hello World");
    char d = 'a'
    size_t len = strlen(name);
    if (len >= (80-1)) DealWithNotEnoughRoom(); 
    name[len++] = d;
    name[len] = '\0';
    

    BTW:
    char *name is not a string literal. "Hello World" above is a string literal.
    char *name is a variable "name as pointer to char".