Mohammed Ashour
Mohammed Ashour

Reputation: 75

adding pointer to integer in C

In the following segment of code:

if (buffer  + strlen(buffer) >= len -1) beep();

note: len is an int, buffer is a pointer to char.

I don't understand how would someone add buffer (a pointer) to the strlen() of a string and compare it to len. Can any one please help me. note: the actual code link is http://www.finseth.com/craft/#intro.1.4 any help will be greatly appreciated.

Upvotes: 0

Views: 103

Answers (2)

M.M
M.M

Reputation: 141586

This code is illegal. A pointer may not be compared to an integer (other than a constant 0). The compiler should have generated an error message.

Some compilers may generate "only" a warning in the default configuration, and perform a nonsensical comparison at runtime, but you should treat this as an error.

You could report this bug to the author of this page; although if basic compilation errors get through their QA process I hate to think what other mistakes might also be present.

Upvotes: 3

Iharob Al Asimi
Iharob Al Asimi

Reputation: 53006

It's called pointer arithmetic, it's essentially the same as

if (&buffer[strlen(buffer)] >= len - 1)

which is a very ugly line of code in both versions.

Why do they compare it to len - 1 is a mistery, unless len is overwritten from the initial value, or the programmer knows exactly what the address of "text" is, which would depend on the compiler AFAIK.

Upvotes: 0

Related Questions