gpt4 book ai didi

c - 使用 char** 数组作为结构成员加载/填充结构,c

转载 作者:行者123 更新时间:2023-11-30 18:12:19 25 4
gpt4 key购买 nike

在过去的两天里,我问了question to load struct ,但是我在循环之外访问我的结构(加载我的结构的循环)时遇到问题。我已经这样编辑了我的问题/和代码:

myfile.txt

Biology,chemistry,maths,music
Mechanics,IT,Geology,music,Astronomy
football,vollyball,baseball

main.c

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

#define path "myfile.txt"

typedef struct student_info
{
char **cources_as_list;
} std_info;

std_info *myinfo; //a global var that will conatain student info
int line_count = 0, cource_count = 0;

char** load_file()
{
char *line = NULL;
size_t len = 0;
FILE *fp;
int indexq=0;
fp = fopen(path, "r");
if (fp == NULL)
{
perror("FILE OPEN ERROR[IN load_file]: ");
exit(1);
}
char **mydata = malloc (sizeof (char *) * 4);//aup to four elements
while (getline(&line, &len, fp) != -1)
{
strtok(line, "\n");
mydata[indexq]= strdup(line);
indexq++;
}
line_count = indexq;
return mydata;
}

char **return_cource_list(char *cources_string) {
char *token;
char **cource_list = malloc(sizeof(char *) * 10);
int index = 0;
//course_string is delimited by ",": (eg. Biology,chemistry,maths,music). parse this and add to my char ** variable.
token = strtok(cources_string, ",");
while (token != NULL)
{
cource_list[index] = strdup(token);
token = strtok(NULL, ",");
index++;
}
cource_count = index;
return cource_list;
}
int main()
{
int i, j;
char** mydata = load_file(); //returns lines as a list/char ** array from file
for (i = 0; i < line_count; i++) //line_count is the number of elements/lines in "mydata"
{
printf("line_data: %s\n",mydata[i]);//i can see all my lines!
char **std_cource_list = return_cource_list(mydata[i]);
for (j = 0; j < cource_count; j++)
{
printf("\tcourse[%d]: %s\n",j,std_cource_list[j]);//i have all my courses as a list from each line
}
//can i load my struct like this? or any option to load my struct?
myinfo[i].cources_as_list = std_cource_list;
}

// i want to see my structure elements here, (nested for loop required).
}

将我的 char 数组加载到我的结构时出现 seg_fault 错误。(即:这一行:myinfo[i].cources_as_list = std_cource_list;)

最佳答案

您需要为您的结构分配内存。

std_info *myinfo = malloc(sizeof(std_info));

也不要将其设置为全局变量,因为此任务中实际上不需要全局变量。

关于c - 使用 char** 数组作为结构成员加载/填充结构,c,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37375522/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com