char * x = "Some string literal"; makes a pointer x that points to (read-only) memory where "Some string literal" resides. Obviously, you shouldn't attempt to modify that memory.
char x[] = "Some string literal"; creates an array of sufficient size and copies the string literal to that array.
void myStrCpy(char[], constchar[]);
int main()
{
char text[128];
cin.getline(text, 128);
char abc[]="ABC";
cout <<"string: "<<text<<endl;
if (myStrCmp(text, abc)==0)
{
cout<<"Your string equals ABC"<<endl<<endl;
}
else
{
cout<<"Your string does not equal ABC"<<endl<<endl;
}
}
void myStrCpy(char text[], constchar abc[])
{
int i;
int temp;
for(i = 0; abc[i] != '\0';i++)
{
temp = abc[i];
text[i]=temp;
}
}
If the Input string length is shorter than ABC, it will give a right compared answer,
AB
string: AB
Your string does not equal ABC
If the input string length is longer than ABC, such as ABCD, since the program will quit working when it see the "\0" of the "ABC", it won't know there is one more "D" there, the output will become:
void myStrCpy(char text[], constchar abc[])
{
// no need for temp variable.
int i ;
for(i = 0; abc[i] != '\0';i++)
text[i] = abc[i] ;
text[i] = '\0' ; // c-strings end with a nul character.
}
I think I shouldn't let the function stop at finding '\0'
But where should I put checking null character then? And what should I put to stop comparing?
The null character is equal to zero. Since c++ (and c) treat non-zero as true, checking for a null terminator can be done like so:
1 2 3 4 5 6 7
int myStrlen(constchar* string)
{
int i = 0;
while (string[i])
i++;
return i;
}
There is no need to check both strings for null terminators (in fact, you will still get the same issue) because the loop would inherently return in the case that "text" is shorter than "abc"
1 2 3 4 5 6 7
//...
res=tempabc-temptext;
if (res!=0)
{
return 1;
}
//...
The simplest solution is to adjust the code after the loop. The loop has ended because abc[i] == null terminator. At that point, if text[i] also == null terminator, then you can say that the strings are equal.
I'm a little surprised the teacher said "no pointers", but that's another story.
I actually have a myStrlen function in the program, as another array, for getting the length of the strings. But that's another assignment requirement. The whole program has 3 functions actually. myStrlen, myStrcmp and myStrcpy
And if i delete this part,
1 2 3 4 5 6 7 8
//...
res=tempabc-temptext;
if (res!=0)
{
return 1;
}
//...
The simplest solution is to adjust the code after the loop. The loop has ended because abc[i] == null terminator. At that point, if text[i] also == null terminator, then you can say that the strings are equal.
Not quite true. Suppose text[] is shorter than abc and the character after the text (assuming it's even memory safe to access and doesn't cause a segmentation fault) is a nul character? That's why you do need to check both strings for termination.