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!!

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]) { …``````

## All 2 Replies

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.

Thanks for the reply, oh ok I see what you're saying; it works great!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of 1.19 million developers, IT pros, digital marketers, and technology enthusiasts learning and sharing knowledge.