我有一个C的任务,并试图解决它几个小时,但尚未成功。
所以我需要读取一个文本文件并将其内容附加到struct类型数组中,
文本文件=>
5 5 7
H1-1哺乳动物生产的乳白色液体
H21IN,用于表示空间、地方或范围内的包含
H3-3公共汽车--一辆可容纳许多乘客的公路车辆
这是代码=>
#define LINESIZE 100
typedef struct
{
char *word; //word and corresponding hint
char *clue;
int x; //Starting x and y positions
int y;
char direction; //H for horizontal, V for vertical
int f; //solved or not
} Word_t;
Word_t* loadTextFile(FILE* file, int numofWords) {
//allocate memory for dynamic array
Word_t *arr = (Word_t*) malloc(sizeof (Word_t) * numOfWords);
char buffer[LINESIZE];
int i = -1; //to skip reading first line, I read it somewhere else
int val;
if (file != NULL) {
while(fgets(buffer, sizeof(buffer), file) != NULL) {
if (i > -1) {
printf("buffer: %s", buffer);
val = sscanf(buffer, "%s %d %d %s %[^\n]", &arr[i].direction, &arr[i].x, &arr[i].y, arr[i].word, arr[i].clue);
printf("print = %s %d %d %s %s\n", &arr[i].direction, arr[i].x, arr[i].y, arr[i].word, arr[i].clue);
}
if (val != 5 && i > -1)
printf("something wrong");
i++;
}
}
fclose(file);
return arr;
}运行代码后,会得到这样的输出
缓冲液:哺乳动物产生的h1-1乳白色液体--打印=哺乳动物缓冲液产生的H1乳白色液体:h21IN,用于表示空间、地点或范围内的包含
进程已完成出口代码-1073741819 (0xC0000005)
这个错误代码意味着我对指针和内存有问题,我认为我对动态类型数组有问题,但我无法解决。请救救我!
发布于 2021-04-28 22:48:20
there.
%s用于读取字符串(以空结尾的字符序列)之前,必须分配缓冲区并分配给word和clue,因此不能用于将一个字符读入char变量direction。为此,您应该使用%c。您可以在此之前添加一个空格,以便让characters.
sscanf()跳过空格%s来打印一个字符,这也是错误的。strings.
%s是用于打印%s的,您应该限制读取的最大长度,以防止malloc()家族的%s结果是considered as a bad practice./* allocate memory */
arr[i].word = malloc(10240);
arr[i].clue = malloc(10240);
/* use correct format specifiers */
val = sscanf(buffer, " %c %d %d %10239s %10239[^\n]", &arr[i].direction, &arr[i].x, &arr[i].y, arr[i].word, arr[i].clue);
printf("print = %c %d %d %s %s\n", arr[i].direction, arr[i].x, arr[i].y, arr[i].word, arr[i].clue);发布于 2021-04-28 22:51:12
问:如何读取文本文件以构造类型数组?
答:您做得很好:为数组分配空间,打开文件,一次读取一行,解析行中的数据并将其读入下一个数组元素。很好:)
问:如何防止0xC0000005 (分段违规)?
答:您需要为结构中的字符串分配空间!
例子:
#define LINESIZE 100
#define MAX_STRING 80
typedef struct
{
char word[MAX_STRING]; //word and corresponding hint
char clue[MAX_STRING];
int x; //Starting x and y positions
int y;
char direction; //H for horizontal, V for vertical
int f; //solved or not
} Word_t;此外:
&arr[i].direction是正确的,但是.%c,而不是%s例子:
val = sscanf(buffer, "%c %d %d %s %[^\n]", &arr[i].direction, &arr[i].x, &arr[i].y, arr[i].word, arr[i].clue);https://stackoverflow.com/questions/67308846
复制相似问题