c++ - Char* 和 While Loop 不能相互配合

标签 c++

这是比较 s2 和 s1 的代码,如果它们相同,则返回 0 和一些其他选项,但是 while 循环不能结束,我找不到它的问题,我唯一知道的是如果我转换 char * s2 转换为 const char* s2 它将正常工作。

#include <iostream>
using namespace std;
int cmp(char*,char*);
int main()
{
    char* s1;
    cout << "Please Enter First Word: "; cin >> s1;
    char* s2;
    cout << "Please Enter Second Word: "; cin >> s2;
    cout << "The Result is: " << cmp(s1,s2) << endl;
       return 0;
}

int cmp(char* s1, char* s2)
{
    int i=0;
    while (*(s2+i)!=0)
    {
        if (*(s2+i)>*(s1+i)) return 1;
        if (*(s2+i)<*(s1+i)) return -1;
        i++;
    }
    return 0;
}

最佳答案

您有未定义的行为。您没有分配任何空间来存储字符串(您没有初始化 s1s2 以指向任何内存)。

我建议改用std::string;它管理自己的内存问题。

关于c++ - Char* 和 While Loop 不能相互配合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9725694/

相关文章:

c++ - 设计更好的API接口(interface),以将结构从一个类传递到另一个类

c++ - 智能指针无法释放内存

android - 如何链接 cpufeatures lib 以获取 native android 库?

c++ - 如何在没有new的情况下在派生对象中使用虚函数?

c++ - 为什么最小 MFC 项目在 Visual Studio 2013 上有链接错误?

c++ - C++中的哈希表/无序映射

c++ - 使用 CryptVerifySignature 的数字签名

c++ - 对 vector 进行排序而不改变原始 vector 的最佳方法是什么?

c++ - 带指针的函数

C++、linux、无需root的关机命令