Search code examples
cstringnullcharterminator

Adding char with null terminator to string in C


What happens when in C I do something like:

char buf[50]="";
c = fgetc(file);
buf[strlen(buf)] = c+'\0';
buf[0] = '\0';

I'm using some this code in a loop and am finding old values in buf I just want to add c to buf

I am aware that I can do:

char s=[5];
s[0]=c;
s[1]='\0';
strcat(buf, s);

to add the char to buf, but I was wondering why the code above wasn't working.


Solution

  • This:

    buf[strlen(buf)] = c+'\0';
    

    will result to this:

    buf[strlen(buf)] = c;
    

    meaning that no addition will take place.

    Thus, what will happen is:

    buf[0] = c;
    

    since strlen(buf) is 0.


    This:

    buf[0] = '\0';
    

    puts a null terminator right on the start of the string, overriding c (which you just assigned to buf[0]). As a result it's reseting buf to "".