最後の2日間でquestion to load structを依頼しましたが、私の構造体にアクセスする際に問題があります。 )。構造体のメンバーとしてchar **配列の構造体をロード/塗りつぶします。
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;
)
'char ** mydata'、' char ** mydata'または 'char ** mydata;'または 'char ** mydata'の中から一番良いものを使用しますが、それらを混同しないでください。 'malloc()'の戻り値を常にチェックし、巨大な割り当てのような特殊な状況下でない限り、固定サイズを 'malloc()'しないでください。 –
あなたはどこにでも 'myinfo'のためのメモリを割り当てません。 –
@JoachimPileborg:私の構造体(myinfo)を割り当てようとしていますが、新しいC言語を使用しています。私はこのようにします** myinfo [i] .cources_as_list = malloc(sizeof(char **)); **。でも同じ問題ですが、あなたは私の構造体をmallocに導くことができますか?ありがとう。 –