0

変数はまだ確定していません! インデントがない場合はすみません。このサイトは初めてです。とにかく、私は 5 つの異なるカテゴリのゲームのリストのテキスト ドキュメントを持っており、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;
}
4

2 に答える 2

2

通常、適切な量のメモリを事前に割り当て、その量が十分でない状況を検出し、そのような場合に割り当てを拡大しますrealloc(またはとmallocが続きます)。このアドバイスは、現在の行を読み込むバッファ ( に渡される) と、すべての行のシーケンスを保持する配列の両方に当てはまります。memcpyfreetempallocateString

but stillを呼び出しfgets(buf, bufsize, fpIn)た後、ライン バッファーのバッファー サイズが不足していることを検出できます。言い換えれば、読み取りがバッファ全体を埋めたが、まだ改行に達していないとき。その場合、次の読み取りは現在の行を続行します。内側のループでバッファを拡張し、必要なだけ再読み取りすることが必要な場合があります。strlen(buf) == bufsize - 1buf[bufsize - 2] != '\n'

allocateStringかなり重複しているため、代わりにそれを使用することをお勧めしますstrdup

上記のテキストのリンクは、主にGNU C ライブラリのマニュアルからのものです。cppreference.comは、C 関数のドキュメントのもう 1 つの優れたソースです。Linux の man ページも同様です。

于 2012-08-02T06:04:05.790 に答える
0
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);
于 2012-08-02T06:51:33.113 に答える