Welcome to the VirtuQ Forums.
Results 1 to 2 of 2
  1. #1

    Strcmp() function in K & R book

    Hi Sir,

    In the book K & R in pg:106 for strcmp() function. I wrote the following program.

    #include<stdio.h>

    int strcmp(char *s, char *t);
    int main()
    {
    char s[]="saketh";
    char t[]="saketh";
    int c;
    c= strcmp(s,t);

    printf("%d",c);
    }

    int strcmp(char *s,char *t)
    {
    for( ;*s == *t;s++,t++)
    if( *s == '\0')
    return 0;

    return *s - *t;
    }

    output:0.

    The function strcmp() is equal to the steps shown in the book. I get correct answer.
    However, i tried to do a small change in strcmp() like below.

    int strcmp(char *s,char *t)
    {
    for( ;*s == *t;s++,t++)
    ;

    return *s - *t;
    }


    which is logically same at the end of the loop both the pointers point to '\0' and i should get the output as 0.
    But when i ran the program i get the output as -4 which means *t pointing to a charecter of ascii value 4.

    Could you please explain why this is happening.

  2. #2
    VirtuQ™ Moderator
    Join Date
    Jul 2011
    Location
    Bangalore, India
    Posts
    1,044
    Blog Entries
    2
    I would say that you should put a printf in the for loop and see how many times the loop is running. In the printf print the value which is being compared.

    Anup


 

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •