Reputation: 406
I've got some code in my program that essentially does this
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");
}
}
When I run it it outputs true no matter what values are in the arrays, even if they are completely different. Why aren't they being compared properly?
Here's the actual code because people can't seem to reproduce my error.
#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;
}
Upvotes: 2
Views: 2013
Reputation: 206567
I suspect the problem is here:
if (same = 1){
That should have been
if (same == 1){
Using -Wall
in gcc reveals the problem quickly.
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){
Upvotes: 7