memcmp,strcmp,strncmp in C

Posted by el10780 on Stack Overflow See other posts from Stack Overflow or by el10780
Published on 2012-10-26T22:57:03Z Indexed on 2012/10/26 23:00 UTC
Read the original article Hit count: 224

Filed under:
|
|

I wrote this small piece of code in C to test memcmp() strncmp() strcmp() functions in C.

Here is the code that I wrote:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(int argc, char** argv)
{
        char *word1="apple",*word2="atoms";

        if (strncmp(word1,word2,5)==0)
                printf("strncmp result.\n");
        if (memcmp(word1,word2,5)==0)
                printf("memcmp result.\n");
        if (strcmp(word1,word2)==0)
                printf("strcmp result.\n");
}

Can somebody explain me the differences because I am confused with these three functions?My main problem is that I have a file in which I tokenize its line of it,the problem is that when I tokenize the word "atoms" in the file I have to stop the process of tokenizing.I first tried strcmp() but unfortunately when it reached to the point where the word "atoms" were placed in the file it didn't stop and it continued,but when I used either the memcmp() or the strncmp() it stopped and I was happy.But then I thought,what if there will be a case in which there is one string in which the first 5 letters are a,t,o,m,s and these are being followed by other letters.Unfortunately,my thoughts were right as I tested it using the above code by initializing word1 to "atomsaaaaa" and word2 to atoms and memcmp() and strncmp() in the if statements returned 0.On the other hand strcmp() it didn't.It seems that I must use strcmp().

I have done google searches but I got more confused as I have seen sites and other forums to define these three differently.If it is possible for someone to give me correct explanations/definitions so I can use them correctly in my source code,I would be really grateful.

© Stack Overflow or respective owner

Related posts about c

    Related posts about string