Satish
Satish

Reputation: 1

strlen in array

I'm debugging a code in which a .ini file is being read for the value of string called Timeout(which is taken into a varibale called rbuf).Please tell me the content of the .ini file when the condition is as follows:

if((strlen(rbuf) > 0) && (rbuf[strlen(rbuf)-1] == '\n')){
    rbuf[strlen(rbuf)-1] = '\0';
   }

When will the debugger go into the above if loop? Please specify the exact content of the rbuf value (Buffer value)

Upvotes: 0

Views: 2295

Answers (2)

Hard to say with the information you have given, but:

(strlen(rbuf) > 0) : rbuf contains a non-empty string (rbuf[strlen(rbuf)-1] == '\n') : rbuf contain a string that ends with a line break.

Other than that, rbuf might only contain a line break. Or it might contian a series of charecters and ends with a line break.

Upvotes: 0

sje397
sje397

Reputation: 41812

When the line has a 'string length' (anything greather than 0, not counting the null-terminator) and the final char before the zero-terminator is a newline, it will enter the conditional block and set that newline to be a null terminator.

In order to tell you the exact contents of rbuf, I would need to know the contents of the ini file. But, for example, if you had a line of text in it like:

i love programming

And lets assume there is an undisplayed newline at the end if it.

Then rbuf would start off containing:

`i love programming\n\0'

Thats 20 bytes. Strlen will return 19 (not including the null-terminator at the end).

rbuf[strlen(rbuf)-1] will be the '\n' character (at index 18 in the buffer).

So your code would see that a newline is at index 18, and set it to '\0', so you end up with:

i love programming\0\0

in your buffer.

Upvotes: 4

Related Questions