检查两个char数组元素是否相同c

时间:2015-10-09 04:03:18

标签: c arrays char compare

我的程序中有一些基本上可以执行此操作的代码

char array[3] = {'g', 'w', 'a'};
char array2[3] = {'h', 'o', 'd'};
int i; 
int b = 1;
for (i = 0; i<=2; i++){
    if (array[i] != array2[i]){
        b = 0;
    }
}
if (b == 1){
    printf("true");
}
else{
    printf("false");
}    

}

当我运行它时,无论数组中的值是什么,它都会输出true,即使它们完全不同。为什么他们没有被正确比较?

这是实际的代码,因为人们似乎无法重现我的错误。

#include <stdio.h>
#include <string.h>
int compare(char word1[], char word2[]){
    int i, k, same = 1, j, a, b;

    for (i =0; i<=79; i++){
        for (k=i; k <= 79; k++){
            if (word1[i] > word1[k]){
                char temp = word1[i];
                word1[i] = word1[k];
                word1[k] = temp;
            }
        }
    }


    for (a =0; a<=79; a++){
        for (b=a; b <= 79; b++){
            if (word2[a] > word2[b]){
                char temp = word2[a];
                word2[a] = word2[b];
                word2[b] = temp;
            }
        }
    }

    for (j =0; j <= 79; j++){
        putchar(word1[j]);
        putchar(word2[j]);
        putchar('\n');
        if (word1[j] != word2[j]){
            same = 0;
        }
    }
    if (same = 1){
        printf("Anagrams");
    }
    else{
        printf("Not Anagrams");
    }
}

int split(char array[]){
    int a, b, c, second = 0, count = 0;
    char word2[80] = "", word1[80] ="";
    for(a=0; a <= 79; a++){
        if (array[a] != 0){
            if (array[a] == ' '){
                second = 1;
                count = 0;
            }
            else{  //add to array
                if (second == 0){
                    word1[count] = array[a];
                    count ++;
                }
                else{
                    word2[count] = array[a];
                    count ++;
                }
            } 
        }
        else{
            break;
        }
    }
    compare(word1, word2);
    putchar('\n');
    return 0;
}
int main(){
    char temp, words[80] = "";
    int count = 0;
    while ((temp=getchar()) != EOF){
        if (temp == '\n'){
            split(words);
            memset(words, 0, 80);
            count = 0;
        }
        else{
            words[count] = temp;
            count ++;
        }
    }
    if (count > 0){
        split(words);
    }
    return 0;
}

1 个答案:

答案 0 :(得分:7)

我怀疑问题在这里:

if (same = 1){

应该是

if (same == 1){

在gcc中使用-Wall可以快速显示问题。

cc -Wall -std=c99     soc.c   -o soc
soc.c: In function ‘compare’:
soc.c:35:5: warning: suggest parentheses around assignment used as truth value [-Wparentheses]
     if (same = 1){