我是一个纯Tcl脚本背景的C语言新手。
我有一个像这样的简单文件。
ship1 Canada
ship4 China
ship5 USA
ship2 UK
ship7 Taiwan
ship6 USA
ship3 Singapore
ship11 Norway
ship8 Senegal
我有一个函数读取这个文件 然后创建一个结构数组并返回这个文件。
// the return type of get_ship_info below is a pointer to struct that contains
// the ship information and the total number of ships counted so far
typedef struct ShipOrigin {
char *ship_name;
int ship_count;
} Ship_origin;
Ship_origin* get_ship_info(FILE*);
int cmp (const void *, const void *);
Ship_origin* get_ship_info(FILE *fp) {
char *line = malloc(sizeof(MAXLINE));
Ship_origin *s_map = malloc(sizeof(*s_map));
int i = 0;
while( (fgets(line, MAXLINE, fp)) != NULL) {
int len = strlen(line);
line[len -1] = '\0';
//printf("%s\n", line);
s_map[i].ship_name = malloc(sizeof(char)*MAXCHAR);
strcpy(s_map[i].ship_name, line);
s_map[i].ship_count = i;
i++;
}
s_map[0].ship_count = i;
return s_map;
}
读取这个文件时,我有一个函数,创建一个数组,并返回这个文件。main
我调用它,并像下面那样使用qsort,这将导致seg故障。
int main(int argc, char *argv[]) {
FILE *fp;
int i;
fp = fopen(argv[1], "r");
Ship_origin *s_origin = NULL;
s_origin = get_ship_info(fp);
int len = s_origin->ship_count;
qsort(s_origin,len, sizeof(s_origin), cmp);
for(i=0; i< s_origin->ship_count; i++) {
printf("SHIP DATA:%s\n", s_origin[i].ship_name);
}
fclose(fp);
return 0;
}
我的 cmp
在qsort中使用的函数,比较了每一个 struct
的元素 s_origin
:
int cmp (const void *a, const void *b) {
Ship_origin* aa = (Ship_origin *) a;
Ship_origin* bb = (Ship_origin *) b;
return strcmp(aa->ship_name, bb->ship_name);
}
我是C语言的新手,很喜欢我所学的东西(由于失业和冠状病毒!)。请帮助我学习我做错了什么。
我也在学习ldb来调试,这和调试Tcl很不一样。它只是显示 stop_reason=EXC_BAD_ACCESS
在 qsort
.
谢谢。
你只分配了一个元素给 s_map
而试图存储多个数据。
你应该像这样重新分配数组。
while( (fgets(line, MAXLINE, fp)) != NULL) {
int len = strlen(line);
line[len -1] = '\0';
//printf("%s\n", line);
s_map = realloc(s_map, sizeof(*s_map) * (i + 1)); // add this
if (s_map == NULL) exit(1); // add this for safety
s_map[i].ship_name = malloc(sizeof(char)*MAXCHAR);
strcpy(s_map[i].ship_name, line);
s_map[i].ship_count = i;
i++;
}
还有第三个参数 qsort
是错误的,应该是要排序的元素的大小,所以不应该是 sizeof(s_origin)
不过 sizeof(*s_origin)
.
也是行 char *line = malloc(sizeof(MAXLINE));
是错误的。这里没有显示,我想 MAXLINE
是一个整数,它的大小最多应该是8个字节,而行会比较长,所以会发生缓冲区超限。它应该是 char *line = malloc(MAXLINE);
.