【发布时间】:2023-03-13 14:57:01
【问题描述】:
我正在尝试做的是将字符串分配给来自单独函数的向量中的指针用于该用途。不幸的是,我不断收到很多警告或错误或总线陷阱: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]);
}
我已经尝试了多种方法,但我认为主要问题是不知道确切的工作原理。这包括将数组传递给函数并将字符串分配给它并为每个指针分配内存。我也一直在这个网站上搜索我的问题,在那里我找到了类似问题的解决方案,但并不完全理解他们的解决方案。如果有人能准确地解释我应该如何工作,我将不胜感激。
提前致谢
【问题讨论】:
-
你为什么要使用指向它的指针来传递
FILE指针?它只需要模拟open函数的引用传递,在其他函数中它只是额外不需要的间接。 -
@Joachim Pileborg 所以下次我在我想要的文件的位置而不是在开头或后面而不是我想要的。我认为这就是它的工作原理。无论哪种方式都可以正常工作,但既然您提到它,我将不胜感激
标签: c arrays string function pointers