【问题标题】:Passing array of pointers to (char) to a function and assigning a string to each将指向 (char) 的指针数组传递给函数并为每个函数分配一个字符串
【发布时间】: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


【解决方案1】:

当你这样做时,例如*dic[e] = malloc(...) 你做错了。表达式*dic[e] 所做的是获取数组dic 的元素e,它是一个指向char 的指针,然后您取消引用该指针为您提供dic[e] 的值是指向。不幸的是,dic[e] 还没有指向任何地方,这将导致未定义的行为,如果编译器没有给您错误,则可能会崩溃。

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

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

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

【讨论】:

  • 谢谢你,我现在明白我做错了什么以及内存泄漏问题......我对此一无所知。我确信我可以继续做我现在正在做的事情。
【解决方案2】:

问题是您错误地处理了指针数组的元素:而不是分配

*dic[e] = malloc(L);

你应该分配

dic[e] = malloc(L);

没有取消引用运算符。

这样做的原因是你传递了一个未初始化的指针数组,所以你不能取消引用它们。但是,您当然可以分配它们,这就是 dic[e] = malloc(L) 所做的。

save_words 也有同样的问题。那里的修复更简单 - 您需要删除 *dic[e] = malloc(125); 行,因为它重新分配了一个已经分配的指针。

最后,您还需要从该行中删除取消引用运算符:

fgets(dic[e],L+1,*read); // No asterisk in front of "dic[e]"

【讨论】:

  • 感谢您的解释
猜你喜欢
  • 1970-01-01
  • 2018-09-16
  • 2016-03-27
  • 1970-01-01
  • 2015-03-17
  • 1970-01-01
  • 2013-04-14
  • 2015-11-25
相关资源
最近更新 更多