使用引用传递String需要进行哪些必要的更改

时间:2018-02-09 14:15:59

标签: c++ string reference pass-by-reference

我正在使用" Pass by Reference"设计用户定义的字符串比较功能。在C ++中。

我的代码在将指针传递给第一个字符时工作正常,但是我很难通过引用传递参数。这是我的代码:

#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;
}

我真的很感激,如果有人请帮助我了解我需要做些什么必要的更改才能使代码通过引用传递参数。 感谢

1 个答案:

答案 0 :(得分:1)

您可以通过C ++中的引用传递C样式数组,以避免它们衰减成指针但是您需要告诉编译器确切地说明您传递的数组的固定大小。以下是两个数组的示例声明。

int StrCmp(const char (&PassedStr1)[100], const char (&PassedStr2)[100]);