C冒泡排序中的分段错误



我有一个包含单词列表的文本文件,每行一个单词,我应该将它们存储在一个数组中,然后按字母顺序对它们进行排序。我被困住了,我需要一些指导。我得到的唯一错误是730 segment fault

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main() {
char *data[45];
int i;
int j;
// OPENS THE FILE
FILE *fp = fopen("/classes/cs3304/cs330432/Programs/StringerTest/TestInput.txt", "r");

if (fp == NULL) {
printf("Unable to open the filen");
} else {
while (fscanf(fp, "%s", data) == 1)
printf("%sn", data);
fclose(fp);
}
char temp[100];

for (i = 0; i < 45 - 1; i++) {
for (j = j + 1; j < 45; j++) {
if (strcmp(data[i], data[j]) > 0) {
strcpy(temp, data[i]);
strcpy(data[i], data[j]);
strcpy(data[j], temp);
}
}
}
for (i = 0; i < 45; i++) {
printf("%s", data[i]);
}
return (0);
}

代码现在可以工作了。比较源文件以确保找到所有差异。主要方面:需要为数据(不仅仅是指针)分配内存。在实践中,您需要找出需要分配多少内存。如果fscanf文件为data,则将其读入data[i]而不是data。不要只使用& 45"在这里。我添加了变量num"存储一定数量的单词。然后,你需要使用"num"同样在循环中,比较"for(j=i+1;j<num;j++)&quot;(j>

#include <stdlib.h>
#include <string.h>
#include <stdio.h>
int main() 
{
char data[45][45];
int i;
int j;
int num;
// OPENS THE FILE
FILE *fp = fopen("test.txt", "r");

if (fp == NULL) 
{
printf("Unable to open the filen");
}
else
{
i=0;
while(fscanf(fp, "%s", data[i]) == 1 )
{
i++;
}
num=i;
}
fclose(fp);
char temp[100];

for ( i=0;i<num-1;i++)
{
for(j=i+1;j<num;j++)
{
if(strcmp (data[i], data[j]) > 0)
{
strcpy(temp,data[i]);
strcpy(data[i], data[j]);
strcpy(data[j], temp);
}
}
}

for (i=0;i<num;i++)
{
printf("%s ", data[i]);
}
// BEGIN: write to file.txt (as asked in comment) 
fp = fopen ("file.txt", "w+");
if(fp==NULL) return 1;
for (i=0;i<num;i++)
{
fprintf(fp,"%s ", data[i]);
}
fclose(fp);
// END: write to file.txt (as asked in comment)
return (0);
}

代码测试:

$ cat test.txt
just a text to test this code
$ ./a.out
a code just test text this to

最新更新