two strings of unknown length. how can we compare them? i am trying the following method. it is giving segmentation fault. I guess the problem is in line 5 and 10 but i cant really figure out what to write there instead of m and n.......
Get the two character arrays. Look at first element in each.
a) if they're different, strings are not the same. Stop
b) if one is zero and the other is not, strings are not the same. Stop
c) if both are zero, the strings are the same. Stop.
b) if both same and not zero, strings could be the same. Move on to next element and repeat.
and about your error if m>n or n>m then you will get the segmentation error because.... the point is when two strings are having different length how they can be equal?
The logic of your comparison look almost right. But if the strings are equal, you have to stop at the null term, so your while loop needs modifying a bit. Also, you need to return 0 if neither of the comparisons hold.
You initial check should be:
1 2 3 4 5 6 7 8 9
if(string1 == string2)
{
cout << "strings are equal" << endl;
return 0;
}
else
{
// do actual comparison...
}
Note that if something isn't "equal", it must be "not equal", so you can use an else! Here I have assumed that you want to see if the addresses of the strings are idential, which would means you comparing a string with itself.
Your example doesn't init the string.
1 2 3 4 5 6 7
constint m = 10; // in ANSI C++, array inti required const size
constint n = 15;
char string1[m] = "";
char string2[n] = "";
strcpy(string1, "hello");
strcpy(string2, "world");