变量还没有被固定下来!如果没有缩进,请原谅。我是新来这个网站的。无论如何,我有一个文本文档,其中列出了五个不同类别的游戏,并且我需要通过typedef来帮助进行内存分配。你会怎么做呢?到目前为止,我得到的是:
/*
Example of text document
2012 DotA PC 0.00 10
2011 Gran Turismo 5 PS3 60.00 12
list continues in similar fashion...
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
//function prototype here
char **readFile(char *file);
char *allocateString(char temp[]);
typedef struct
{
int year;
char name[100];
char system[10];
float price;
int players;
}game;
int main(void)
{
char **list;
system("pause");
return 0;
}
//function defined here
char **readFile(char *file) //reads file and and allocates
{
FILE* fpIn;
int i, total=0;
fpIn = fopen("list.txt", "r");
if (!fpIn)
{
printf("File does not exist");
exit(101);
}
/*
allocate memory by row here VIA for loop with the total++ to keep track of the
number of games
*/
/*
allocate memory individually for each item VIA "allocateString by using going
to set list[i] = allocateStrng(tmpList) using for loop the for loop will have
for (i=0; i<total; i++)
*/
return;
}
//allocateString here
char *allocateString(char temp[]);
{
char *s;
s = (char*)calloc(strlen(temp+1), sizeof(char)));
strcpy(s, temp);
return s;
}发布于 2012-08-02 14:04:06
通常,您会预先分配相当数量的内存,检测到该数量不足的情况,并在这些情况下使用realloc (或使用malloc,然后使用memcpy和free)来扩大分配。这个建议既适用于读取当前行的缓冲区(作为temp传递给allocateString),也适用于保存所有行序列的数组。
在调用fgets(buf, bufsize, fpIn) strlen(buf) == bufsize - 1但仍为buf[bufsize - 2] != '\n'时,可以检测到行缓冲区的缓冲区大小不足。换句话说,当reach填满了整个缓冲区,但仍然没有到达换行符时。在这种情况下,下一次读取将继续当前行。您可能需要一个内部循环来扩展缓冲区,并再次读取所需的时间。
请注意,您的allocateString几乎复制了strdup,因此您可能希望使用它。
以上文本中的链接主要来自manual of the GNU C library。cppreference.com是另一个很好的C函数文档来源。the Linux man pages也是如此。
发布于 2012-08-02 14:51:33
s = (char*)calloc(strlen(temp+1), sizeof(char)));
//the name of the array is a pointer, so you are doing pointer arithmetic.
//I think you want strlen(*temp+1, sizeof(char)));
// or strlen(temmp[1]) it isn't clear if this is a pointer to a string or an array
// of strings
//you need the length of the string *temp is the content which temp points to
//strcpy(s, temp);https://stackoverflow.com/questions/11771801
复制相似问题