【发布时间】:2014-12-02 22:33:03
【问题描述】:
这是一个程序,它按照某些规则生成诸如“aaabaabaaa”(或只是空字符串)之类的单词,一切正常,它生成它,按大小排序,然后按字母顺序但是当我实现阻止生成相同单词的部分时给我“分段错误(核心转储)”
我的问题是什么原因造成的,我该如何解决?
(我在 Ubuntu 14.04 上通过 gcc 编译器使用 Code::Blocks)
整个程序
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
void bsas(int n, char **words);
void as(int n, char **words) {
int rn = rand();
strcat(words[n], "a");
if(rn % 3 == 0) as(n, words);
if(rn % 3 == 1) bsas(n, words);
}
void bsas(int n, char** words){
int rn, j;
for(j=0; j<2; j++){
if(j == 0)
strcat(words[n], "b");
else
strcat(words[n], "a");
rn = rand();
if(rn % 3 == 0) as(n, words);
if(rn % 3 == 1) bsas(n, words);
}
}
static int compareCombo(const void * a, const void * b){
if (strlen(*(const char **) a) < strlen(*(const char **) b))
return -1;
else if (strlen(*(const char **) a) > strlen(*(const char **) b))
return 1;
else
return strcmp (*(const char **) a, *(const char **) b);
}
int main()
{
int rnum = 0, i, j, n;
char** words;
srand(time(NULL));
system("clear");
printf("\n Opis gramatyki: \n S->aS|bSaS|ε \n");
getchar();
printf("Ile chesz wygenerowac lancuchow? "); /*means how much words do you want to generate*/
scanf("%d", &n);
words = (char**) malloc(n*sizeof(char*));
for (i = 0; i < n; i++)
{
words[i] = (char*) malloc(40000*sizeof(char));
}
for(i=0; i<n; i++){
rnum = rand();
if(rnum % 3 == 0) as(i, words);
if(rnum % 3 == 1) bsas(i, words);
if(rnum % 3 == 2) ;
/*:PROBLEM OCCURS when I add this: */
**for(j = i-1; j >= 0; j--){
if(strcmp(words[i], words[j]) == 0){
words[i] = "";
i--;
break;
}
}**
/*
this should check if there are some duplicates among words
if there are any it should erase it, and try to generate it again
*/
}
qsort (words, n, sizeof (const char *), compareCombo);
for(i = 0; i < n; i++){
printf("%d\t- %s\n", i+1, words[i]);
}
return 0;
}
出现错误的部分:
/*:PROBLEM OCCURS when I add this: */
for(j = i-1; j >= 0; j--){
if(strcmp(words[i], words[j]) == 0){
words[i] = "";
i--;
break;
}
}
/*
this should check if there are some duplicates among words
if there are any it should erase it, and try to generate it again
*/
【问题讨论】:
标签: c gcc segmentation-fault