954,499 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

Comparing two character arrays using an if

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?

Mal-man
Newbie Poster
1 post since Mar 2011
Reputation Points: 10
Solved Threads: 0
 

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().

gerard4143
Nearly a Posting Maven
2,272 posts since Jan 2008
Reputation Points: 512
Solved Threads: 387
 

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?

WaltP
Posting Sage w/ dash of thyme
Moderator
10,506 posts since May 2006
Reputation Points: 3,348
Solved Threads: 944
 

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.

harish9
Newbie Poster
4 posts since Mar 2011
Reputation Points: 7
Solved Threads: 0
 

The function strcmp() is used for comparing two strings

darkdai
Light Poster
27 posts since May 2010
Reputation Points: 9
Solved Threads: 0
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You
View similar articles that have also been tagged: