我在将项目添加到C中的2d指针数组时遇到麻烦。我的代码如下:
#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
数组中的每个指针(假设您要解决的问题是分配一个数组而不是单个字符)都指向内存中的同一字符串。
要解决这些问题,您应该遵循以下伪代码:
input
以存储指向您将要读入的每个单词的指针。input
以指向刚读入的这个单词如果您在将此过程转换为C代码时遇到困难,请提出一个新问题让我们知道。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句