我在启动程序时遇到了一些麻烦。我是新手。我做了一些研究并找到了一些资源,但是我将它应用于代码时遇到了麻烦。它主要基于指针和结构。
我主要需要帮助学习如何在结构中存储数据,以及如何初始化所有内容。
程序应该找到文件中字符的频率。我需要使用动态内存分配。并使用动态分配的指针数组来存储字符和频率。我应该使用malloc()来分配数组,并使用realloc()来增加数组的大小以插入更多的元素。但我不知道该怎么做。
该程序使用这些功能 -
•charInCFStruct:返回charfreq结构的索引,其中charc存储在其成员变量中。如果charfreq结构都不包含c,那么它必须返回-1。
•printCFStruct:打印所有charfreq结构的内容。
•freeCFStruct:释放所有charfreq结构,然后释放指针 结构。
到目前为止,我知道这是正确的。我觉得从那里重新开始会更容易。我并不是要求准确的代码,只是对我需要做的主题的一些帮助,并推动正确的方向。谢谢!
#include <stdio.h>
#include <stdlib.h>/*
* struct for storing a char and the number of times it appears in a provided text */
struct charfreq
{
int count;
char next;
};
typedef struct charfreq charfreq;
/*
* Returns the index of charfreq struct which has the char c stored in its member variable next.
* If none of the charfreq structs contains c then it returns -1.
*/
int charInCFStruct(charfreq **cfarray, int size, char c){
}
/*
* Prints the contents of all of the charfreq structs.
*/
void printCFStruct(charfreq **cfarray, int size){
}
/*
* Frees all of the charfreq structs and then frees the pointer to the structs.
*/
void freeCFStruct(charfreq **cfarray, int size){
}
int main(void)
{
charfreq **cfarray;
FILE *inputfile;
char next;
int size = 10; /* used initial value of 10 but any positive number should work */
int i = 0;
int pos;
/* open file to read from */
inputfile = fopen("chars.txt", "r");
if(inputfile == NULL)
printf("chars.txt could not be opened. Check that the file is in the same directory as you are running this code. Ensure that its name is chars.txt.\n\n");
/* allocate space for pointers to char frequency structs */
cfarray = (charfreq**)malloc(size*sizeof(charfreq*));
/* read in chars until the end of file is reached */
while(fscanf(inputfile, "%c", &next) != EOF){
/* fill in code to fill structs with data being read in */
/* call to increase space after changing size */
cfarray = realloc(cfarray,size*sizeof(charfreq*));
}
/* print out char frequency structs */
printCFStruct(cfarray,i);
/* free all char frequency structs */
freeCFStruct(cfarray,i);
/* close the file we opened earlier */
fclose(inputfile);
return 0;
}