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

标签 c arrays struct

在过去的两天里,我问了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/

相关文章:

php - 将复选框 PHP 表单项作为数组插入到 MySQL 数据库

c++ - 如何将数据从一个结构链接到另一个结构

c - 编写一个函数来返回节点的位置

c - 如何在C中定义结构体数组?

c# - 从多个数字数组创建平均数组的最快方法

vb.net - Visual Basic 中未知长度的数组

C - #define 宏内的双下划线

将 volatile int 转换为 int8_t 进行输出

c++ - 获取结构中元素的数量

结构编译器错误 vector 的 C++ 迭代器