0

Hi , i have problem with return value , program returning 1 even if str , text or both are null

int prefix  ( char *str , char *text  ) {

    int len = strlen (text);
    if (str == NULL)
            return 0;

    else if (text == NULL )
            return 0;
    else {
            for (int i=0 ; i<=len-1 ; i++) {
                if (text[i]==str[i])
                    printf (" %d char equal \n",i);
                 else return 0;
         }

         return 1 ;

     }
}


int main () {

    int result = prefix ("","");

    printf ("%d\n",result);
}
missimer
  • 4,022
  • 1
  • 19
  • 33
uppermost
  • 1
  • 5

2 Answers2

2

Firstly, the string "" is different from the string NULL. "" is a char* with a single '\0' character, and NULL is nothing.

Your problem here is that when you pass empty strings, the two checks are passed, and then for loop never executes because the strings don't have any characters (0 <= -1 is false). Therefore there is never a chance to return 0, and thus the return 1 is always called.

Adam Evans
  • 2,072
  • 1
  • 20
  • 29
1

"" is not NULL it is the empty string. Also you should have to check for NULL before strlen as strlen does not check for NULL.

Community
  • 1
  • 1
missimer
  • 4,022
  • 1
  • 19
  • 33