c - Need help understanding what strncmp function in for loop is doing -


i dont understand happening in code below in strncmp function. why (all+j*100)+i?

/* search jth string in char all[][100] *pat*/ int patternsearch( int j, char *all, char *pat ) {      int i;      ( i=0; < strlen(all+j*100); i++ )     {         if ( strncmp(pat, ((all+j*100)+i), strlen(pat)) == 0 )         {             return(i);  // *pat found @ ith byte of all[j]         }     }      return(-1); // *pat not found in all[j] } 

it great if please explain me in detail going on in loop.

the comment in first line explains all. array all divided in chunks of 100 characters, , argument j tells chunk start looking pattern. strncmp applied positions starting @ beginning of jth chunk, until end of array. return offset of character pattern found relative beginning of jth chunk.


what (all+j*100)+i do?

the j*100 gets index of first element of jth chunk of array. is, if j 2, obtains 200 index of first element of 2nd chunk (the chunk @ start zeroth chunk).

all+j*100 same &all[j*100], getting pointer element (or beginning of chunk) talked about, in case &all[200].

finally +i incrementing pointer i, , i iterator of loop @ first pass input strncmp() &all[200], , &all[201], , &all[202] , on until pattern found or end of array reached.

the choice of literal 100, , using divide array chunks, seems choice made programmer of function. not needed, call function j=0 , search pattern done without using 100 anything. programmer knew in arrays, patterns found few hundred characters array, gave caller chance start looking pattern j-hundred characters array search done faster.


example - imagine literal 5 instead of 100 simplicity, with:

arr = "abcdefghijklm"; pat = "gh"; 

if argument passed j=0, first strncmp in loop called &arr[0] looking @ 'a' character, second &arr[1] looking @ 'b' , on until pattern found. it'll found on 'g' (&arr[6]) return 6.

if argument passed j=1, first strncmp in loop called &arr[5] looking @ 'f' character, second &arr[6] looking @ 'b' pattern found , 1 returned.


Comments

Popular posts from this blog

java - nested exception is org.hibernate.exception.SQLGrammarException: could not extract ResultSet Hibernate+SpringMVC -

sql - Postgresql tables exists, but getting "relation does not exist" when querying -

asp.net mvc - breakpoint on javascript in CSHTML? -