本文介绍了功能分配,主功能不可用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试为main中的char数组指针数组分配空间并将文件数据放入函数中.运行程序时出现分段错误.谁能告诉我为什么?
I am trying to allocate space and put in file data in my function for my array of char arrays pointer in main. I get a segmentation fault when I run the program. Can anyone tell me why?
datawords [0]在该函数中正确打印.
datawords[0] is printed correctly in the 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数组的指针,以便在主体中使用分配.
You need to pass to the function a pointer to the data_words array in order to use the allocation in the 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]);
}
我不确定是否所有*都正确,有时会令我感到困惑,但想法是将指针传递给该函数.
I am not sure if I got all the * right it gets me confused sometimes but the idea is to pass a pointer to the function.
这篇关于功能分配,主功能不可用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!