Reputation: 3
I'm designing a user defined String Compare function using "Pass by Reference" in C++.
My code is working fine when passing a pointer to the first character, but I'm struggling to pass the argument by reference. This is my code below:
#include <iostream>
int StrCmp(char [], int, char []);
int main()
{
char Str1[100], Str2[100];
int Compare = 0, StrSize1 = 10; //Both strings are having same number of alphabets.
std::cout<<"Input the First String: "<<std::endl;
gets(Str1);
std::cout<<"Input the Second String: "<<std::endl;
gets(Str2);
Compare = StrCmp(Str1, StrSize1, Str2);
if (Compare == 1)
std::cout<<"String 1 *"<<Str1<<"* is Greater Than String 2 *"<<Str2<<"*"<<std::endl;
else if(Compare == -1)
std::cout<<"String 1 *"<<Str1<<"* is Smaller Than String 2 *"<<Str2<<"*"<<std::endl;
else if(Compare == 0)
std::cout<<"Both String 1 *"<<Str1<<"* and String 2 *"<<Str2<<"* are Equal"<<std::endl;
return 0;
}
int StrCmp(char PassedStr1[], int Size1, char PassedStr2[])
{
for(int i=0; i<Size1 ; ++i)
{
int CodeAscii_1 = PassedStr1[i];
int CodeAscii_2 = PassedStr2[i];
if(CodeAscii_1 > CodeAscii_2)
return 1;
else if(CodeAscii_1 < CodeAscii_2)
return -1;
}
return 0;
}
I would really appreciate if someone please help me understand what necessary changes I need to do to make the code work for passing the argument by reference. Thanks
Upvotes: 0
Views: 56
Reputation: 2278
You can pass C style arrays by reference in C++ to avoid having them decay into pointers but you need to tell the compiler exactly the fixed size of the array you're passing. Here is an example declaration for your two arrays.
int StrCmp(const char (&PassedStr1)[100], const char (&PassedStr2)[100]);
Upvotes: 1