4 Years
Discussion Span
Last Post by luvrahul30

I mean to say if we compare strings then we use strcmp but its strncmp here and also "&" is used which isn't used usually...that's what i am asking if could make me understand the meaning of this line...if say char line[].......& also why sscanf is used???


strcmp - compares 2 strings up to their zero terminator
strncmp - compares 2 strings up to a limit of either their zero terminator or a supplied count of characters. This is useful if you happen to want to look for a specific substring of characters within a larger string.

You don't just have an & you also have [] which are important in this context. The entire expression is &line[j].

Assuming that line is defined something like char line[100];, strings are just arrays of characters there is nothing particularly special about them in C except that the last character must always be the NUL terminator '\0'.

In this case you are presumably used to calling strcmp like this

strcmp(line, "text");

You need to understand what the expression line does in this case. When you use an array name without the [] then the evaluated expression returns a pointer to the first item in the array and as a type of pointer to the type of the array, in the case of line this is char*. So is there any other way to get a pointer to the first item in the array? We case use [] to access items in the array some line[0] is the first item in the array. To get the address of the first item in the array we can use the address of operator which is & so &line[0] also returns a pointer to the first item in an array, line and &line[0] are functionally equivilent (they return the same thing, a pointer to the first item in the array).

Now compare &line[0] to the expression you are interested in &line[j]. The only difference is that 0 is replaced j, the [j] selects the jth item in the array and as before the & gets the address of it so the expression &line[j] returns a pointer to the jth item in the array.

Putting it all together then in the statement if(strncmp(&line[j],"MEMBERED",8)==0) this gets a pointer to the jth item in line and calls strncmp to compare the first 8 characters found there with the string "MEMBERED" the result is tested ==0 and if the data in line matched the string the code in the if statement is exectuted (like strcmp strncmp returns 0 when it gets a match).

good explanation
This article has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.