Search code examples
carrayspointerschar

Assigning char to char* using pointers


Let's say I have a char *str and I want to assign it characters one by time using using pointers and incrementing ?

I've done :

char *str;
char c = 'a';
*str++ = c;

But it doesn't work.

How can I do that ?


Solution

  • str is just a pointer. It doesn't point anywhere valid (especially not to some memory you could write to). A simple possibility would be to have it point to an array:

    char buf[1024] = {0}; // room for 1024 chars (or 1023 + a 0 byte for a string)
    char *str = buf;
    char c = 'a';
    *str++ = c;