It just prints an empty line.
You are unfortunate, but not surprisingly so, that your code's undefined behavior manifests as printing an apparently-empty string. It would have been more indicative of the nature of the problem if it threw a segfault, or some other variety of memory-related violation, as would be entirely appropriate.
Why does it do this
Because you are performing arithmetic on the pointer, not modifying the thing to which it points. This expression ...
string += 'A';
... computes the pointer addition of string
with the integer character constant 'A'
(whose numeric value is system dependent, but is often the ASCII code for capital letter A), and stores the resulting pointer in string
. This makes string
point to something different than it previously did. It does not in any way modify the contents of the memory to which string
pointed.
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?
If you have an upper bound on how long the data can be, then the easiest thing to do is declare a large-enough array to contain the data and initialize it to all-zero ...
char string[MAX_LEN + 1] = {0};
You can then add a single character by by writing it to the next available index (which index you may either track, or compute at need via strlen()
):
unsigned next_index = 0;
string[next_index++] = 'A';
string[next_index++] = 'B';
string[next_index++] = 'C';
Note that this relies on the zero-initialization -- which is not automatic for local variables -- to ensure that the array contents at all times comprise a null-terminated string. Having done that, you can print the expected result:
printf("%s\n", string);
If you did not know in advance a reasonable upper bound on how long the string may be, or if the upper bound were exceedingly large, then you would need to relying on dynamic memory allocation and reallocation. This is a subject for you to defer until later.