Adding char with null terminator to string in C

jes.alpha picture jes.alpha · Aug 12, 2017 · Viewed 18.4k times · Source

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.

Answer

PSkocik picture PSkocik · Aug 12, 2017

Why would it work?

char buf[50]=""; initializes the first element to '\0', strlen(buf) is therefore 0. '\0' is a fancy way of a saying 0, so c+'\0'==c, so what you're doing is

buf[0]=c;
buf[0]=0;

which doesn't make any sense.

The compound effect of the last two lines in

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

is a no-op.