1

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.

3
  • 2
    Note that c+'\0' is just c. It does not write two elements to the array. Commented Aug 12, 2017 at 18:49
  • 1
    buf[0] = '\0'; reset buf to null-string(""). Commented Aug 12, 2017 at 18:51
  • sample code Commented Aug 12, 2017 at 20:30

3 Answers 3

3

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

1
 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;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.