2013-03-10 83 views
0

正如标题所说,我必须使用指针构建一个趋势函数。函数将检查第二个字符串是否出现在第一个字符串的末尾,如果它返回1则返回1,否则返回0 。这里是我的代码,它不是编译的,它在赋值错误中给出了一个非左值。任何想法?使用指针构建趋势函数

#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; 
} 

回答

3

编译器显示的错误表明您正在尝试分配的东西不是LVALUE。简单来说LVALUE是指可以在赋值的左侧出现的词语,(实际上它远比这更复杂;))

您需要使用==为相等比较,而不是=

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

还要注意的是,编译器显示错误的*s2 = '\0'并没有抱怨的第一个任务*s1 = '\0'(即使它在逻辑上是不正确的程序要求)。

换句话说,编译器不会显示的左值误差只有这样的说法:

if (*s1 = '\0') 

只有当你有一个&& *s2 = '\0',它表现出了错误。

而且作为teppic在下面的评论中指出,这是因为表达式相当于if(*s1 = ('\0' && *s2) = '\0') (由于运算符的优先级),这使编译器显示LVALUE错误,因为表达式中不能有0 = 0

+0

大声笑,感谢队友......我从来没有想过关于特定错误:P,我甚至有另一个错误里面放的1输出,即使第二个字符串是在第一个发现的(即使它最终没有结束)。 – Lind 2013-03-10 21:42:49

+0

虽然代码不正确,但是错误是由于它试图将0赋给'('\ 0'&& * s2)',即0 = 0;' – teppic 2013-03-10 21:57:45

+0

@teppic - 这是不正确的,这样的代码分配。例如,试试这个简单的例子,你会看到我在说什么:'int a,b;如果(a == 1 && b = 2)'会给你一个错误,但是如果你只有'if(b = 2)',编译器不会显示错误。 – Tuxdude 2013-03-10 22:02:56

0

我需要将*s2!='\0'添加到第一个For条件。

0

看看这个片段。

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;