0

As the title says,I must build a strend function with pointers.The function will check if the second string appears at the end of the first string and return 1 if it does or 0 if it doesnt.Here is my code,it is not compiling and its giving an non lvalue in assigment error.Any ideas?

#include <stdio.h>
#define MAX 100
int strend (char *s1,char *s2);
int main()
{
    char string1[MAX]="Check Mate";
    char string2[MAX]="Mate";
    printf("The Result is :\n");
    printf("%d",strend(string1,string2));
    return 0;
}
int strend (char *s1,char *s2)
{
    for(;*s1!='\0';s1++)
                        { for(;*s2!='\0' && *s1!='\0' && *s1==*s2;s1++,s2++)
                                       ;
                                       }
    if(*s1='\0' && *s2='\0')
                return 1;
    else 
                return 0;
}
4

3 回答 3

3

The error shown by the compiler indicates that you are trying to assign to something which is not an LVALUE. In simple terms LVALUE refers to the terms which can appear on the left hand side of an assignment, (in reality it is much more complex than that ;) )

You need to use == for the equality comparison instead of =

if (*s1 == '\0' && *s2 == '\0')
    return 1;
else 
    return 0;

Also note that the compiler was showing the error at *s2 = '\0' and was not complaining about the first assignment *s1 = '\0' (even though it is logically incorrect to your program requirement).

In other words the compiler would not have shown the LVALUE error with just this statement:

if (*s1 = '\0')

Only when you had an && *s2 = '\0', it showed the error.

And as teppic pointed out in the comments below, it is because of the expression being evaluated equivalent to if(*s1 = ('\0' && *s2) = '\0') (because of operator precedence) which made the compiler show the LVALUE error, since you cannot have 0 = 0 in an expression.

于 2013-03-10T21:40:03.390 回答
0

I needed to add *s2!='\0' to the first For condition.

于 2013-03-10T21:46:18.830 回答
0

Check out this snippet .

char str1[50]="Check Mate";
char str2[50]="Mate";
int flag,i,l1,l2;

l1=strlen(str1);
l2=strlen(str2);
/*
 * Place a pointer to the end of strings 1 and strings 2 . 
 */
char *ptrend1 = (str1+l1-1);
char *ptrend2 = (str2+l2-1);


flag = 1; 
for(i=l2;i>0;i--)
{
    /*
     * Keep traversing such that in case the last charachters of the stings
     * dont match break out . 
     */
    if(*ptrend2 != *ptrend1){
        flag = 0 ;
        break;
    }
    /*
     * Decrement both the end pointers 
     */
    ptrend1--;
    ptrend2--;
}
if(flag)
    printf("String 2 is contained at the end of string 1");
else 
    printf("String 2 is NOT contained at the end of string 1");
return 0;
于 2013-03-11T04:02:12.720 回答