简体   繁体   English

无法找出我的程序崩溃的原因

[英]couldnt find out why my program is crashing in c

Using Dev C++ on windows 7 64 bit 在Windows 7 64位上使用Dev C ++

I was trying to implement ac program that identifies the word with most occurrences in a sentence in the most optimal way. 我试图实现一个ac程序,以最佳方式识别句子中出现次数最多的单词。 This is what i created.. 这就是我创造的......

 struct word{
    char *str;
    int count;
    };

int main()
{
    struct word words[10]={0};
    int i,j,flag=0,max=0;
    char *maxw=NULL,*arr[] = {"how","do","you","do"};


    for(i=0;arr[i];i++)
    {
        flag =0;
        for(j=0;words[j].count!=0;j++)
            if(strcmp(words[j].str,arr[i]) == 0 )
            {
                words[j].count++;
                flag = 1;
                break;
            }

        if(flag == 0){  
        words[j].str = arr[i];
        words[j].count++;
        }

        if (max < words[j].count){
        max = words[j].count;
        maxw=words[j].str;
        }
    }
    printf("\nMost occurrences is of %s with %d count",maxw,max);

    getch();
    return 0;
}

What i have figured out already is that the program crashes only when the maximum occurring word is the also the last word of the sentence and this has something to do with addresses of fixed strings in the memory. 我已经想到的是,只有当最大出现的单词也是句子的最后一个单词时,程序才会崩溃,这与内存中固定字符串的地址有关。 But i am not sure exactly what is happening here. 但我不确定这里到底发生了什么。 Also, is this a good solution to this problem or some more optimum solution exists ?? 此外,这是一个很好的解决这个问题的方法还是存在一些更优化的解决方案?

PS This is not homework i am just practicing some coding. PS这不是作业,我只是练习一些编码。

Your array of pointers is not null terminated, but in your loop you are checking for null like : 你的指针数组不是以null结尾,但是在你的循环中你要检查null,如:

for(i=0;arr[i];i++)

So you should null terminate your arr like 所以你应该null终止你的arr类的

char *maxw=NULL,*arr[] = {"how","do","you","do",NULL}

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

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