我正在编写一个程序,该程序将文本文件作为输入,对其进行索引并在文件和屏幕中打印输出(索引)。
输入文件可能很大。但我们知道文本文件中使用的单词的最大种类是 200。我们不知道每个单词的行数和字符数是多少。所以我应该为他们保留大量。我取了最大行1000,每个单词最大字符数100。
我正在使用 Turbo C 编程并且(我被迫使用它)。编译器仅分配 64kb 内存(包括编译器的大小),因此我必须使用 MALLOC。
我的程序应该在这个算法中工作:它用 fgets 逐行读取输入文件。然后在当前行中,它使用 strtok 逐字读取。到目前为止,我在第 y 行中有第 x 个单词。我想把单词放在一个指针数组中。所以我需要一个 char * word[200]。我想显示多少次,哪个词在哪一行重复了。所以我需要一个 int 索引 [200][1000]。如果在第 y 行,第 x 个单词存在,我会做索引[x][y]++。
所以现在我需要为这些 char * word[200] 和 int index[200][1000] 分配 MALLOC 内存。谁能帮忙?我尝试了这些问题的所有答案,但都没有帮助。 查看错误:
char **words;
words = malloc(sizeof(char*) * 200);//cannot conver void * to char **
for(int i = 0; i < 200; i++)
words[i] = malloc(100);//cannot convert void * to char *
int **index;
index = malloc(sizeof(int*) * 200)//cannot convert void * to int **
for (i = 0; i < 200; i++)
index[i] = malloc(sizeof(int) * 1000);
最佳答案
malloc
函数返回一个void *
对象,您可以将其视为“指向未定义类型的指针”。当您不知道指针指向哪种对象时,这是 C 格式化指针的方式。
Turbo C 发出的错误意味着您不允许将 void *
分配给不同类型的指针(例如 char **
变量或 int *
) 而不是将其显式转换为该类型。您可以通过这样编写 malloc 调用来做到这一点:
char **words;
words = (char **) malloc(sizeof(char*) * 200);
for(int i = 0; i < 200; i++)
words[i] = (char *) malloc(100);
int **index;
index = (int **) malloc(sizeof(int*) * 200);
for (i = 0; i < 200; i++)
index[i] = (int *) malloc(sizeof(int) * 1000);
如今从 malloc
转换结果非常不受欢迎,但如果您必须使用将隐式指针转换视为错误的编译器,那就见鬼去吧。 :-)
关于c - 如何在访问数组和二维数组时通过 c 中的 malloc 分配最大长度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20337110/