简体   繁体   English

分段错误c ++为什么我的程序给我分段错误

[英]segmentation fault c++ why is my program giving me segmentation fault

Why is my code has segmentation fault? 为什么我的代码存在分段错误? I am trying to see if there is two same letters in a string. 我正在尝试查看字符串中是否有两个相同的字母。 But how come it has segmentation fault? 但是为什么会有分割错误呢?

#include<iostream>
#include<cstring>
using namespace std;

bool match(char[], int);

int main()
{
    char word[20];
    cout << "Enter a word: ";
    cin >> word;
    int length = strlen(word);
    if (match(word, length)) cout << "It has two letters that are the same" <<
        endl;
    else cout << "There is no same letters" << endl;
    return 0;
}

bool match(char word[], int length)
{
    bool found = false;
    for (int i = 0; i < length; i++)
    {
        for (int j = 1; i < length; j++)
        {
            if (j <= i || j == length || i == length) continue;
            if (word[i] == word[j]) found = true;
        }
    }
    return found;
}

Did you intentionally include i in your j loop or was that accidental? 您是否有意将i包含在j循环中,还是偶然?

Reference: 参考:

 "for (int j = 1; i < length; j++)"

Should this be: for (int j; j<length; j++)?

Keep in mind some seg faults have memory management issues, not just logical issues. 请记住,某些段错误涉及内存管理问题,而不仅仅是逻辑问题。 Check to make sure your sizeof operator is functioning correctly, that's what I usually screw up 检查以确保您的sizeof运算符正常运行,这就是我通常搞砸的事情

There's a typo here: 这里有一个错字:

for (int j = 1; i < length; j++)

where you wrote i instead of j , which means that your loop will never stop. 您在其中写了i而不是j ,这意味着您的循环将永远不会停止。
Reading outside the array is undefined, and by blind luck you got a crash instead of something that appeared to work. 数组外的读取是不确定的,而碰巧的是,您崩溃了,而不是看起来有用的东西。

Of the conditions in your inner loop, two are pointless ( j == length and i == length ) because of the loop conditions. 在内部循环中,由于循环条件,两个条件是无意义的( j == lengthi == length )。
The third only makes you not do anything useful for the first i iterations. 第三个仅使您在第一个i迭代中没有做任何有用的事情。
A better way of accomplishing this is to not do anything at all by starting the loop at i + 1 . 一种更好的方法是完全不执行任何操作,只需在i + 1处启动循环即可。

bool match(char word[], int length)
{
    for (int i = 0; i < length; i++)
    {
        for (int j = i + 1; j < length; j++)
        {
            if (word[i] == word[j])
            {
                return true;
            }
        }
    }
    return false;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM