我想做的就是从一个单独的函数中为向量中的指针分配字符串。不幸的是,我一直收到很多警告或错误或公共汽车陷阱: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 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]);
}
我已经尝试了多种方法,但是我认为主要的问题是无法确切地知道它们是如何工作的。这包括将数组传递给函数,并为其分配字符串,并为每个指针分配内存。我也一直在这个网站上搜索我的问题,在那里我找到了类似问题的解决方案,但并不清楚他们的解决方案。如果有人能确切解释我应该如何工作,我将不胜感激。
提前致谢
当您这样做时,例如*dic[e] = malloc(...)
您做错了。表达式*dic[e]
所做的是获取e
数组的element dic
,它是指向的指针char
,然后取消引用该指针即可为您提供所指向内容的值dic[e]
。不幸的是,dic[e]
它还没有指向任何地方,如果编译器没有给您错误,这将导致未定义的行为和可能的崩溃。
而且,由于尝试将返回的指针分配给不是指针的对象,因此会出现错误malloc
。
那么解决方案呢?删除取消引用,然后执行例如dic[e] = malloc(...)
。
当您尝试从中的文件读取字符串时,也会遇到相同的问题save_words
。那里还有另一个问题,您再次为该字符串分配了内存,从而使该alloc
函数的原始分配丢失了,并导致内存泄漏。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句