[英]Segmentation fault while trying to sort strings in C
I am simply trying to read from a text file, parse some information into an "array of strings" and then alphabetize the array using qsort.我只是想从文本文件中读取,将一些信息解析为“字符串数组”,然后使用 qsort 对数组进行字母排序。 However, I keep getting a segmentation fault during the sorting part.
但是,我在排序部分不断收到分段错误。 I am new to C, can anybody take a look at my code and tell me what the problem is?
我是 C 新手,有人可以看看我的代码并告诉我问题是什么吗?
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
int compare (const void * a, const void * b ) {
return strcmp(*(char **)a, *(char **)b);
}
int main(int argc, char* argv[]){
FILE *fp;
fp = fopen(argv[1], "r"); // argv[1] = "input.txt"
char allStrings[255][255];
int stringArrCounter = 0;
char buff[255]; /* String to put the scanned shit in*/
char blank[255];
strcpy(blank, " ");
int counter = 0;
while (!feof(fp)){
char stringer[255];
char stringer2[255];
fgets(buff, 255, fp);
if (strcmp(buff, blank) > 0){
if (counter % 5 == 0){
strncpy(stringer, buff, strlen(buff)-1);
}
else if (counter % 5 == 1){
strncat(stringer, buff, strlen(buff)-1);
}
else if (counter % 5 == 3){
strncpy(stringer2, buff, strlen(buff)-10);
strncat(stringer2, stringer, strlen(stringer));
}
else if (counter % 5 == 4){
strcpy(allStrings[stringArrCounter], stringer2);
printf("%s\n", stringer2);
memset(stringer,0,sizeof(stringer));
memset(stringer2,0,sizeof(stringer2));
stringArrCounter++;
}
counter++;
}
}
qsort(allStrings, 255, sizeof(char *), compare);
}
Here is a short example of how to use qsort
with a 2-D array.以下是如何将
qsort
与二维数组一起使用的简短示例。 Note that a 2-D array is different to an array of pointers.请注意,二维数组与指针数组不同。 It is a contiguous bloc of characters and the compiler will compute offsets in response to the dimensions you give.
它是一个连续的字符块,编译器将根据您提供的尺寸计算偏移量。
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
int comp10(void const *p1, void const *p2)
{
typedef char const A[10];
return strcmp( *(A *)p1, *(A *)p2 );
}
int main()
{
char arr[3][10] = { "pangolin", "fish", "anteater" };
qsort(arr, sizeof arr / sizeof arr[0], sizeof arr[0], comp10);
for (int i = 0; i < sizeof arr / sizeof arr[0]; ++i)
printf("%s\n", arr[i]);
}
Setting up the comparison function and the qsort
call correctly is your main issue.正确设置比较函数和
qsort
调用是您的主要问题。
However your code to read the strings from file contains a number of mistakes.但是,您从文件中读取字符串的代码包含许多错误。 Please consult the manual pages for
strncpy
and strncat
and fgets
to see what the arguments mean and what output they generate.请查阅
strncpy
和strncat
和fgets
的手册页以了解参数的含义以及它们生成的输出。 See here for how to use feof
(hint: you should not use it at all). 请参阅此处了解如何使用
feof
(提示:您根本不应该使用它)。
I would recommend you divide your program into two parts:我建议您将程序分为两部分:
Once both tests succeed , then you can feed the output of (2) into the input of (1).一旦两个测试都成功,那么您可以将 (2) 的输出输入到 (1) 的输入中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.