Cant Add Characters To A Char Pointer Assigned To ""
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?
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 = "";
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
If a character array already contains a string like
char string = "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( string, "C" );
In any case the character array shall have enough space to accommodate a new character.
- → OctoberCMS Backend Loging Hash Error
- → "failed to open stream" error when executing "migrate:make"
- → OctoberCMS - How to make collapsible list default to active only on non-mobile
- → Create plugin that makes objects from model in back-end
- → October CMS Plugin Routes.php not registering
- → OctoberCMS Migrate Table
- → How to install console for plugin development in October CMS
- → OctoberCMS Rain User plugin not working or redirecting
- → October CMS Custom Mail Layout
- → October CMS - How to correctly route
- → October CMS create a multi select Form field
- → How to update data attribute on Ajax complete
- → October CMS - Conditionally Load a Different Page