Ad

Cant Add Characters To A Char Pointer Assigned To ""

- 1 answer

Say I have this code

char *string = "";
string += 'A';
string += 'B';
string += 'C';
printf("%s\n", string);

It just prints an empty line. Why does it do this and is there an easy way to concatenate single characters starting from an empty string if I don't know how long it'll be?

Ad

Answer

In statements like this

string += 'A';

there is used the pointer arithmetic. The value of the internal representation of the character 'A' is added to the value of the pointer string and as a result the pointer has an invalid value because it does not point to an actual object.

You need to declare a character array as for example

char string[4] = "";

and then you can set respective elements of the array to character literals like for example

int i = 0'
string[i++] = 'A';
string[i++] = 'B';
string[i++] = 'C';
string[i] = '\0';

printf("%s\n", string);

Also you have a typo in this call

printf("&s\n", string);

If a character array already contains a string like

char string[4] = "AB";

and you want to append a character to the end of the string then either you can write using a character literal

size_t n = strlen( string );
string[n] = 'C';
string[n + 1] = '\0';

Or you can use a string literal and the standard C function strcat like

strcat( string, "C" );

In any case the character array shall have enough space to accommodate a new character.

Ad
source: stackoverflow.com
Ad