function分配,主要无法使用

我正在尝试分配空间并将我的函数中的文件数据放入main中的char数组指针数组中。 运行程序时出现分段错误。 谁能告诉我为什么?

数据字[0]在函数中正确打印。

这是我的function:

void database_extract (char **data_words) { FILE *f_data; f_data = fopen("database.txt","r"); struct stat st; stat("database.txt", &st); data_words = (char **)malloc(st.st_size * sizeof(char)); if (data_words == NULL) { printf("No room\n"); exit(EXIT_FAILURE); } data_words[0] = "test"; printf("%s",data_words[0]); } 

这是我的主要内容:

 int main () { char **data_words; database_extract (data_words); printf("%s",data_words[0]); } 

任何帮助将不胜感激。

您需要向函数传递一个指向data_words数组的指针,以便在main中使用该分配。

试试这个:

 void database_extract (char ***data_words) { FILE *f_data; f_data = fopen("database.txt","r"); struct stat st; stat("database.txt", &st); *data_words = (char **)malloc(st.st_size * sizeof(char)); if (data_words == NULL) { printf("No room\n"); exit(EXIT_FAILURE); } data_words[0] = "test"; printf("%s",data_words[0]); 

}

在主要:

 int main () { char **data_words; database_extract (&data_words); printf("%s",data_words[0]); 

}

我不确定我是否得到了所有*对,它有时让我感到困惑,但想法是传递一个指向函数的指针。

当你想要一个函数初始化的东西时,你需要在函数调用中使用& ,在函数签名中使用一个额外的*

 void database_extract (char ***data_words) { 

与…匹配

 database_extract (&data_words);