Stuck on a program i've been trying to work on for the last few hours.

A user enters 2 arrays, both are charater arrays with 5 spaces each.
They are passed into a function that compares the 2 arrays to each other character by character. If they are idenital the user is informed of this.

void comp(char string1[], char string2[])
{
	int i;
	for(i = 0; i < 5; i++)
	{
		if(string1[i] == string2[i])
		{
			printf("they are the same.\n");
		}
		else
		{	
			printf("they are not the same.\n");
		}
	}
}

This is what i have so far but from my googling it seems like you can't use "==" operators to compare to character array spaces.
Anyways around this or am i missing something obvious?

Recommended Answers

You can use the == operator to compare the elements of the character array which is what your doing in the above code. If you want to compare c-strings then you could use strcmp().

Jump to Post

All 4 Replies

You can use the == operator to compare the elements of the character array which is what your doing in the above code. If you want to compare c-strings then you could use strcmp().

Stuck on a program i've been trying to work on for the last few hours.

A user enters 2 arrays, both are charater arrays with 5 spaces each.
They are passed into a function that compares the 2 arrays to each other character by character. If they are idenital the user is informed of this.

void comp(char string1[], char string2[])
{
	int i;
	for(i = 0; i < 5; i++)
	{
		if(string1[i] == string2[i])
		{
			printf("they are the same.\n");
		}
		else
		{	
			printf("they are not the same.\n");
		}
	}
}

This is what i have so far but from my googling it seems like you can't use "==" operators to compare to character array spaces.
Anyways around this or am i missing something obvious?

Yes. An explanation of your problem with the code. As I see it, the loop and IF are OK, although the contents of the IF probably will cause a problem.

Run through your code with pencil and paper. What happens?

You are comparing two strings str1 & str2 character by character. When character are same if condition is satisfied and prints equal, When character are not equal it comes else part and prints unequal. When compairing character by character use running pointer.

The function strcmp() is used for comparing two strings

Be a part of the DaniWeb community

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