0

Hi all, I have a question about comparing the contents of characters in arrays to see if they are the same.

When I try and do something like this:

char output_1[5];
char output_2[5];

int i; 

for (i = 0; i < 5; i++)
{
    if (table_1[i][0] == table_x1[i])
    {
        output_1[i] = 'n';
    }

    if (table_1[i][1] == table_x1[i])
    {
        output_1[i] = 'j';
    }
}

for (i = 0; i < 5; i++)
{
    if (table_2[i][0] == table_x2[i])
    {
        output_2[i] = 'n';
    }

    if (table_2[i][1] == table_x2[i])
    {
        output_2[i] = 'j';
    }
}

printf("out 1 : %s \n", output_1 );
printf("out 2 : %s \n", output_2 );

if (output_1 == output_2)
{
    printf("are equivalent\n");
}

else
    printf("not equivalent\n");

The print shows the strings are the same ( both produce "njnj") but the comparison always says they are "not equivalent" when they should be.

Any help is greatly appreciated!!

2
Contributors
2
Replies
4
Views
4 Years
Discussion Span
Last Post by noahjonesnoah
1

Arrays cannot be compared with the == operator. You really have no choice but to loop over the elements and compare them onesie twosie:

int equal = 1; /* Equal until proven otherwise */
int i;

for (i = 0; i < 5; ++i) {
    if (output_1[i] != output_2[i]) {
        equal = 0;
        break; /* No need to continue the comparison */
    }
}

if (equal)
    puts("are equal");
else
    puts("not equal");

This is assuming the arrays are of equal length, of course.

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.