c - typedef 内存分配

标签 c variables

变量尚未一成不变!如果没有缩进,请原谅。我是这个网站的新手。无论如何,我有一个包含五个不同类别的游戏列表的文本文档,并且我需要通过 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;
}

最佳答案

通常,您会预先分配相当数量的内存,检测该数量不足的情况,并在这些情况下使用 realloc 扩大分配。 (或 malloc 后跟 memcpyfree )。此建议适用于您读取当前行的缓冲区(作为 temp 传递给 allocateString)和保存所有行序列的数组。

调用 fgets(buf, bufsize, fpIn) 后,您可以检测到行缓冲区的缓冲区大小不足strlen(buf) == bufsize - 1 但仍然是 buf[bufsize - 2] != '\n'。换句话说,当读取填满整个缓冲区时,但仍然没有到达换行符。在这种情况下,下一次读取将继续当前行。您可能需要一个内部循环来扩展缓冲区并再次读取所需的时间。

请注意,您的 allocateString 几乎重复 strdup ,所以您可能想使用它。

以上文字中的链接主要来自manual of the GNU C librarycppreference.com是 C 函数文档的另一个很好的来源。正如 the Linux man pages .

关于c - typedef 内存分配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11771801/

相关文章:

python - 验证失败后从空表单数据中检索空字符串

c - 从 C 代码设置 ALSA 主音量

c - 如何使用c获取总线和开发信息

c - ARM 程序集 : Access array elements residing in C type struct

c - 编译 C 程序时,出现此错误 : hello: no such file or directory

javascript - Udacity 冰淇淋测验 - Javascript 语句/条件

variables - OBIEE 存储库变量和 session 变量之间的区别

arrays - 检查经典 asp 数组中的变量是否存在

variables - 带有变量列表的Stat.exists

c - 实现一个像设备一样的菜单,每个命令都没有条件