将指向(char)的指针数组传递给函数,并为每个函数分配一个字符串
我想做的是从一个单独的函数中为向量中的指针分配字符串。不幸的是,我一直收到很多警告或错误或总线陷阱:10 以下是到目前为止我在这里评论的问题代码:将指向(char)的指针数组传递给函数,并为每个函数分配一个字符串,c,arrays,string,function,pointers,C,Arrays,String,Function,Pointers,我想做的是从一个单独的函数中为向量中的指针分配字符串。不幸的是,我一直收到很多警告或错误或总线陷阱:10 以下是到目前为止我在这里评论的问题代码: #include <stdio.h> #include <stdlib.h> void read_top(FILE **read,short int *L, short int *D, short int *N){ fscanf(*read,"%hd %hd %hd",L,D,N); // L being the si
#include <stdio.h>
#include <stdlib.h>
void read_top(FILE **read,short int *L, short int *D, short int *N){
fscanf(*read,"%hd %hd %hd",L,D,N); // L being the size of the strings, D being how many strings there are and N doesn´t matter for this question
fgetc(*read); // remove \n
}
void save_words(FILE **read,char **dic,short int L,short int D){ // i´m having problems here assigning strings to the pointers
int e;
for (e = 0;e < D;e++){
*dic[e] = malloc(125);
fgets(*dic[e],L+1,*read);
fgetc(*read);
}
}
void open(FILE **read,FILE **write) {
*read = fopen("teste4.in","r");
*write = fopen("Allien_language","w");
}
void alloc(char **dic,D,L){ //i´m having problems here allocating memory for each pointer to point to
int e;
for (e = 0;e < D; e++){
*dic[e] = malloc(L);
}
}
main(){
FILE *read,*write;
open(&read,&write);
short int L,D,N;
read_top(&read,&L,&D,&N);
char *dic[D]; // here´s the array of pointers
alloc(dic,D,L); // here´s the funtion i can´t get to work
save_words(&read,dic,L,D); // here´s the function that i can´t get to work
//printf("\n%s\n",dic[0]);
}
#包括
#包括
无效读取(文件**读取,短整数*L,短整数*D,短整数*N){
fscanf(*read,“%hd%hd%hd”,L,D,N);//L是字符串的大小,D是有多少个字符串,N对这个问题不重要
fgetc(*读取);//删除\n
}
void save_words(FILE**read,char**dic,short int L,short int D){//我在为指针分配字符串时遇到问题
INTE;
对于(e=0;e
我尝试了很多方法,但我认为主要的问题是不知道事情是如何运作的。这包括将数组传递给函数,为其分配字符串,并为每个指针分配内存。我也一直在这个网站上搜索我的问题,在那里我找到了类似问题的解决方案,但并不完全理解他们的解决方案。如果有人能准确地向我解释事情应该如何进行,我将不胜感激
当您这样做时,请提前感谢,例如,
*dic[e]=malloc(…)
您做错了。表达式*dic[e]
所做的是获取数组dic
的元素e
,该元素是指向char
的指针,然后您取消引用该指针,给出dic[e]
所指向的值。不幸的是,dic[e]
还没有指向任何地方,这将导致未定义的行为,如果编译器没有给您一个错误,可能会导致崩溃
您会得到一个错误,因为您试图将malloc
返回的指针分配给非指针的对象
那么解决方案呢?删除取消引用,只需执行例如dic[e]=malloc(…)
在
save\u words
中尝试从文件中读取字符串时,也会遇到同样的问题。还有另一个问题,您再次为字符串分配内存,使alloc
函数的原始分配松动,并导致内存泄漏。问题在于您错误地处理指针数组的元素:而不是赋值
*dic[e] = malloc(L);
dic[e] = malloc(L);
你应该指派
*dic[e] = malloc(L);
dic[e] = malloc(L);
没有解引用操作符
这样做的原因是您正在传递一个未初始化指针数组,因此可能无法取消对它们的引用。但是,您当然可以分配它们,这就是dic[e]=malloc(L)
所做的
您在保存单词
中也遇到同样的问题。这里的修复更简单-您需要删除*dic[e]=malloc(125)代码>行,因为它会重新分配已分配的指针
最后,您还需要从此行中删除取消引用运算符:
fgets(dic[e],L+1,*read); // No asterisk in front of "dic[e]"
为什么要使用指向文件的指针传递指针?只需为您的open
函数模拟按引用传递,在其他函数中,它只是多余的间接引用。@Joachim Pileborg,以便下次我在我想要的文件位置,而不是在开始或后面。我想这就是它的工作原理。无论哪种方式都可以,但我希望你能澄清一下,既然你提到了,谢谢你,我现在明白我做错了什么,以及内存泄漏问题。。。我对此一无所知。我相信我可以继续做我现在正在做的事。谢谢你的解释