gpt4 book ai didi

c - 将指向(char)的指针数组传递给函数并为每个函数分配一个字符串

转载 作者:行者123 更新时间:2023-12-01 13:47:18 25 4
gpt4 key购买 nike

我想做的是将字符串分配给来自单独函数的 vector 中的指针以供该用途。不幸的是,我不断收到很多警告或错误或总线陷阱: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数组 dic , 这是指向 char 的指针,然后你取消引用给你值的指针 dic[e]指向。遗憾dic[e]还没有指向任何地方,这将导致未定义的行为,如果编译器没有给您错误,则可能会导致崩溃。

然后你得到一个错误,因为你试图分配 malloc 返回的指针指向不是指针的东西。

那么解决方案呢?删除取消引用,然后执行例如dic[e] = malloc(...) .

当您尝试从 save_words 中的文件中读取字符串时遇到同样的问题.你还有另一个问题,你为字符串再次分配内存,使你失去了从alloc的原始分配。功能,并导致内存泄漏。

关于c - 将指向(char)的指针数组传递给函数并为每个函数分配一个字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34989079/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com