小编Bo *_*uan的帖子

使用qsort时出现分段错误

我正在研究一个程序来读取txt文件并对字符串进行排序.

data.txt中:

jk ef ab cd bc gh fg ij hi de 
Run Code Online (Sandbox Code Playgroud)

这是我的代码:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <ctype.h>

int cmp(const void *p1, const void *p2) {
    return strcmp(*(const char **)p1,  *(const char **)p2);
}

int main() {
    FILE *f = fopen("data.txt", "r");
    char s[255][255];
    char tmp[255];
    int n = 0;

    while (!feof(f)) {
        fscanf(f, "%s", tmp);
        strcpy(s[n], tmp);
        n++;
    }

    fclose(f);

    qsort(s, n, sizeof(char *), cmp);

    int i = 0;
    for …
Run Code Online (Sandbox Code Playgroud)

c qsort segmentation-fault

2
推荐指数
2
解决办法
986
查看次数

标签 统计

c ×1

qsort ×1

segmentation-fault ×1