Expression: string subscript out of range

1
2
3
4
5
6
7
8
int equals(string str1, string str2) //return 1 if str 1 == str2, 0 if str1 > str2 || str2 > str1.
{
	int i, j;
	for( i=0; str1[i]!=NULL; i++);
	for( j=0; str2[j]!=NULL; j++);
	return i==j;

}


When running this function, there is an error showing that "Expression: string subscript out of range."

What is the cause of this?

How to solve it?

Thank you in advance :)
It could be that std::strings are not null terminated. They have a method length() for that.
By the way, you realise that this is far from what a function called "equals" should do, right?
Oh thank you... I 've just known that there is a method called length... next time i programme i will use it

However, in this homework, we are not allowed to use string method...

I still have some questions...

1) what do you mean by " this is far from what a function called "equals" should do" ?

2) how is string terminated?
Compare your function with the standard function strcmp and you will see the difference.
1) A function called equals should test to see if the two strings are equal, which I believe is what you are attempting to do, however it doesn't actually get done here.

2) Strings are containers. They aren't "terminated" so much as they are a list of characters, and anything past the end just returns either a null_ptr or an undefined result (depending on your compiler)

3) You shouldn't return i == j; from int equals(std::string, std::string); function, you'd want to return that evaluation from bool equals(std::string, std::string);
Topic archived. No new replies allowed.