c - 无法正确地将文件中的条目添加到指针的二维数组中

标签 c arrays

我在将项目添加到 C 中的二维指针数组时遇到问题。我的代码如下:

#include <stdio.h>
#include <stdlib.h>
#include <malloc/malloc.h>
#include "pg3_methods.h"

void load_input(char path[])
{
char ** input = (char**)malloc(sizeof(char));

// Variable to hold current word
char * currentWord = malloc(sizeof(char));

// Set file equal to the path
FILE * file;
file = fopen(path, "r");
int i = 0;

// Checks if file is null
if (file == NULL)
{
    fprintf(stderr, "File %s does not exist.", path);
}

// If not null, cycles through file and adds entries
while (!feof(file))
{
    fscanf(file, "%s", currentWord);
    input = (char**)malloc(sizeof(char)*1);
    input[i] = currentWord;
    printf("input[%i] = %s\n", i, currentWord);
    i++;
}
for (int i = 0; i < sizeof(input); i++)
{
    printf("%s\n", input[i]);
}
}

输出是这样的:

input[0] = The
input[1] = small
input[2] = fox
input[3] = jumped
input[4] = over
input[5] = the
input[6] = red
input[7] = fence
input[8] = bad
input[9] = The
input[10] = small
input[11] = fox
input[12] = jumped
input[13] = over
input[14] = the
input[15] = red
input[16] = fence
input[17] = bad
input[18] = The
input[19] = small
input[20] = fox
input[21] = jumped
input[22] = over
input[23] = the
input[24] = red
input[25] = fence
input[26] = bad

(null)
(null)
bad
(null)
(null)
bad
(null)
(null)

正如你所看到的,它在 while 循环内工作,但是一旦退出循环,一切就变得一团糟。关于我如何完成这项工作有什么建议吗?任何帮助将不胜感激! (注意:输出第一部分中的单词来自单独的文本文件。)

最佳答案

char ** input = (char**)malloc(sizeof(char));

这为单个字符分配了足够的内存,这可能不是您想要的。相反,你应该这样做:

char ** input = (char**)malloc(sizeof(char*) * WORD_COUNT);

它将分配几个指向char的指针。您现在可以将其视为 char* 数组。

char * currentWord = malloc(sizeof(char));

同样,您只分配一个字符。您可能需要分配比这更多的内存。

现在让我们看看 while 循环的主体:

fscanf(file, "%s", currentWord);
input = (char**)malloc(sizeof(char)*1);
input[i] = currentWord;

这里有几个问题。首先,你不断地重写内存中的前一个单词。其次,您为输入分配了一个新的内存块,并忘记了分配的旧内存块(这是内存泄漏)。最后,input 数组中的每个指针(假设您修复了分配数组而不是单个字符的问题)都指向内存中的同一字符串。

要解决这些问题,您应该遵循以下伪代码:

  1. 输入分配足够的内存,以存储指向您将读入的每个单词的指针。
  2. 在循环中:
    1. 为一个单词分配内存
    2. 将字读入分配的内存
    3. input中的一个指针分配给刚刚读入的这个单词

如果您在将此过程转换为 C 代码时遇到困难,请提出新问题告诉我们。

关于c - 无法正确地将文件中的条目添加到指针的二维数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26111184/

相关文章:

javascript - 跨浏览器 "inArray"函数(没有 jQuery)

c - C 编程语言中的递归

c - 结构副本与成员副本(时间效率)

c - C 中的全局变量不会跨线程更新

arrays - 如何从React中的对象数组中仅返回3个元素

arrays - 如何将数组或列表转换为 hashref?

使用c中的用户输入和函数计算数组的总和和平均值

c - 这是 C 标准中整数类型符号位定义的错误吗?

c - 为灵活性和处理分配内存的更好方法

java - 在 2D int 数组算法中收集重复值的索引