Domanda

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?

È stato utile?

Soluzione

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".

Altri suggerimenti

You have defined name as a pointer to a fixed location in memory (probably in the initialized data segment). You need not a pointer, but a vector with enough size to accomodate the original string and the string you want to append to.

char d[100];  /* enough room for a string of 99 characters */

strcpy (d, "a");  /* initialize d with string "a" */
strcat (d, "b");  /* append "b" to d, resulting in "ab" */

If you want to append a single character stored in a char variable, you may do as this:

char c='b';
char d[100];  /* enough room for a string of 99 characters */

strcpy (d, "a");  /* initialize d with string "a" */
d[strlen(d)+1]='\0'; /*  add the character stored in c to string d */
d[strlen(d)]=c;      /*            resulting in "ab"               */
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top