我一直收到相同的消息“细分错误:11”gdb告诉我断点在main函数之后。在我声明int j的行中;我真的不明白怎么可能破坏代码。
此函数读取的输入仅由1个字符串后跟2个数字组成,例如
约翰22 43萨姆11 23
它要做的只是将整个输入存储在“ elenco”中,然后打印字符串。
首先,我创建了一个与输入匹配的结构。然后我做了一个函数,目的是读取输入并将其存储在变量中。然后我做了一个函数,其变量是函数的输出,该函数读取输入(因此为input),并打印给定的字符串
有人可以帮助我确定问题并解决吗?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct
{
char name[20];
int distance;
int point;
} throw;
throw *read_file(FILE *f, int *j)
{
int i = 0;
int c;
int Dim = 32;
char buf[1000];
throw *list;
list = malloc(Dim *sizeof(*list));
if (list == NULL)
{
(*j) = 0;
return NULL;
}
while (fgets(buf, sizeof(buf), f)!= NULL)
{
sscanf(buf, "%19s %d %d",
list[*j].name,
&list[*j].distance,
&list[*j].point);
*j += 1;
if ( *j >= Dim)
{
Dim = Dim*2;
list = realloc(list, Dim *sizeof(*list));
if (list == NULL)
{
return NULL;
}
}
}
return list;
}
void print_everything(throw *list, int j)
{
int c;
for (c=0; c < j; c++ )
{
printf("%d\n",list[c].distance);
}
}
int main(int argc,const char *argcv[])
{
int j = 0;
FILE *file;
throw *list;
if (!( argc != 3))
{
printf("file's dimension is wrong\n");
return -1;
}
file = fopen(argcv[1], "r");
list = read_file(file, &j);
print_everything(list, j);
fclose(file);
return 0;
}
input1.txt
马里奥20 30乔治30 40马里奥40 40戴维德32 20马里奥9 32
正是文件所包含的内容
您的程序很好。您的问题是在input1.txt中,您需要
Mario 20 30
Giorgio 30 40
Mario 40 40
Davide 32 20
Mario 9 32
使用fgets()读取时,每行都需要一个\ n
对代码进行了一些更改,使列表使用错误,尝试使用指针
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAXSTR 250
typedef struct elenco
{
char *name;
int distance;
int point;
struct elenco *next;
} throw;
throw *list_add(throw *list, int distance, int point, const char *name)
{
throw *new = malloc(sizeof(throw));
if (new != NULL) {
new->distance = distance;
new->point = point;
new->name =(char*)malloc(strlen(name)+1);
strcpy(new->name,name);
new->next = list;
return new;
}
return list;
}
throw *read_file(FILE *f)
{
char buf[MAXSTR];
throw *list = malloc(sizeof(throw));
while (fgets(buf, sizeof(buf), f)!= NULL)
{
char name[MAXSTR];
int distance;
int point;
sscanf(buf, "%s %d %d",
name,
&distance,
&point);
list = list_add(list, distance, point, name);
}
return list;
}
void print_everything(throw *list)
{
while (list) {
printf("%d\n",list->distance);
list = list->next;
}
}
int main()
{
int argc;
const char *argcv;
FILE *file;
if (!( argc != 3))
{
printf("file's dimension is wrong\n");
return -1;
}
file = fopen(&argcv[1], "r");
throw *list = read_file(file);
print_everything(list);
fclose(file);
return 0;
}