[Pure C] Negative array index in practice

You know that array can be indexed with negative index: array[-1]. Here is the example, why it can be used.

Search a word within a buffer, like 'java'. But on word boundary. Skip 'javascript' or 'sunjava'.

const char* s="java";
size_t s_len=strlen(s);
const char* x=memmem(buf, len, s, s_len);
if (x!=NULL && isalpha(x[-1])==0 && isalpha(x[s_len])==0)
{
        // found at address x
};

But beware: corner/marginal cases are not checked, like if the 'java' word is at the very beginning of the buffer. Or at the very end. (I didn't add these checks to make my demonstration code short and simple.)

UPD: This my idea is criticised at reddit.

(the post first published at 20240124.)


List of my other blog posts.

Subscribe to my news feed.

Yes, I know about these lousy Disqus ads. Please use adblocker. I would consider to subscribe to 'pro' version of Disqus if the signal/noise ratio in comments would be good enough.