0

次の点を考慮してください。

typedef struct wordType
{
    char word;
    uint count;
};

int main( void ) 
{
    typedef struct wordType * WORD_RECORD;
    WORD_RECORD arrayOfWords = malloc(10 * sizeof( WORD_RECORD) );

    FILE * inputFile;
    char temp[50];
    uint index;
    inputFile = fopen( "input.txt", "r"); 

    while( fscanf( inputFile, "%s", temp) == 1 )
        {
        printf("%s\n", temp );
        arrayOfWords[index].word = malloc( sizeof(char)*(strlen(temp) + 1 ));

        strcpy( arrayOfWords[index].word, temp );
    }
    index++;
}

scanf を介して単語が取り込まれるたびに malloc しようとしています。しかし、なぜこれがうまくいかないのか分かりません。エラーが発生しています:

warning: assignment makes integer from pointer without a cast

warning: passing argument 1 of ‘strcpy’ makes pointer from integer without a cast
4

2 に答える 2

2

c 文字列は char* 型です。あなたが言う時

char word;

全体ではなく、1 つの文字に十分なスペースを確保しています。単語型を char* にする:

char* word;

カウントを設定することを忘れないでください。

さらに、10 行を超えて読み取らないと、別のメモリ エラーが発生することに注意してください。

于 2013-04-29T21:47:03.040 に答える
1

文字列として使用したいword。文字列は null で終わる文字の配列であるため、 type を指定する必要がありますchar*。各単語にメモリを動的に割り当てるため、free後で各単語を呼び出すようにしてください。

tempまたは、 50 文字の配列であり、ハードコードwordを同じようなサイズにするという事実を利用することもできます。

最後のマイナー ポイントsizeof(char)は 1 であることが保証されているため、malloc計算を簡略化できます。

于 2013-04-29T21:50:07.993 に答える