jes.alpha
jes.alpha

Reputation: 37

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.

Upvotes: 1

Views: 41999

Answers (3)

0___________
0___________

Reputation: 67999

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

probably they wanted

buf[length_of_the_string_stored_in_the_buf_table] = c;
buf[length_of_the_string_stored_in_the_buf_table + 1] = 0;

same removing last char

char *delchar(char *s)
{
    int len = strlen(s);
    if (len)
    {
        s[len - 1] = 0;
    }
    return s;
}

Upvotes: 1

Petr Skocik
Petr Skocik

Reputation: 60145

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.

Upvotes: 3

gsamaras
gsamaras

Reputation: 73444

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 "".

Upvotes: 1

Related Questions