【问题标题】:Comparing char* in C比较 C 中的 char*
【发布时间】:2014-04-25 12:02:57
【问题描述】:

我正在尝试比较位的模式,为此我有一个将模式保存为字符串的结构。然后我想将该字符串与我构建的另一个字符串进行比较。我正在使用 strcmp,但是它匹配两个字符串,即使它们不匹配。 这是我的代码

typedef struct
{
    int emp;
    char *context;
    int numOnes;
    int numZeros;


}Pattern;

char *patt, str[t+1];
    patt = str;
    while(count<t){
        //printf("Stream: %d\n", stream[end]);
        if(stream[end] == 1){
            patt[count]= '1';
            //writeBit(1);
        }
        else{
            patt[count]='0';
            //writeBit(0);
        }


        end--;
        count++;
    } //code to build a string

while(i<(1<<t)&&(found==0)){
        if((strcmp(patt,patterns[i].context)==0)){
            if(patterns[i].numOnes <= patterns[i].numZeros){
                prediction = 0;
                checkPredict(prediction,stream[end], i);
            }
            else{
                prediction = 1;
                checkPredict(prediction,stream[end], i);
            }
            found = 1;

        }
        else{
            found = 0;
        }
        i++;
    }//comparing string

【问题讨论】:

  • I am using strcmp, however it is matching two strings even though they do not match. 你是怎么识别的?你调试了吗?通过打印值进行调试。

标签: c string strcmp


【解决方案1】:

您永远不会终止patt,即在最后一个字符之后写入'\0' 字符。因此,它不是一个有效的字符串,因此您不能在其上使用strcmp()

【讨论】:

  • strcmp 需要一个以 null 结尾的字符串,至少在大多数实现中是这样。请参阅implementation by Apple,它应该与 BSD 中使用的类似。
  • @no92 这不是我刚才说的吗?我不明白你的评论。
  • 我并不是说你的答案是错误的。我只是补充说它是必需的。另请注意,gcc 会在需要(并且可能)时自动添加它,因此如果他仅将 char * 用于字符串,您的回答可能毫无意义。
  • @no92 我阅读了问题中的代码,我知道patt 在他调用strcmp() 时是一个未终止的字符串。这就是我的回答所说的。我同意代码本身也很混乱,但这些部分似乎很清楚。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-02-09
  • 1970-01-01
  • 1970-01-01
  • 2021-12-28
相关资源
最近更新 更多