功能分配,主要无法使用

时间:2013-12-01 19:59:35

标签: c function malloc

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

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

这是我的功能:

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]);
}

非常感谢任何帮助。

2 个答案:

答案 0 :(得分:2)

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

void database_extract (char ***data_words) {

匹配
database_extract (&data_words);

答案 1 :(得分: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]);

}

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

相关问题