我在将项目添加到 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
数组中的每个指针(假设您修复了分配数组而不是单个字符的问题)都指向内存中的同一字符串。
要解决这些问题,您应该遵循以下伪代码:
- 为
输入
分配足够的内存,以存储指向您将读入的每个单词的指针。 - 在循环中:
- 为一个单词分配内存
- 将字读入分配的内存
- 将
input
中的一个指针分配给刚刚读入的这个单词
如果您在将此过程转换为 C 代码时遇到困难,请提出新问题告诉我们。
关于c - 无法正确地将文件中的条目添加到指针的二维数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26111184/