c - 来自输入文件的动态分配

标签 c malloc strcpy

考虑以下几点:

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

最佳答案

C 字符串是 char* 类型。当你说

char word;

您只为一个角色留出了足够的空间,而不是整个角色。使单词类型为char*:

char* word;

不要忘记设置计数。

此外,您可能要注意不要阅读超过 10 行,否则会出现另一个内存错误。

关于c - 来自输入文件的动态分配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16288744/

相关文章:

c - IRB 无法运行 ruby​​ gem 函数,而 ruby​​ 成功

c++ - strcpy... 想替换为 strcpy_mine,它将 strncpy 和 null 终止

c - 在 Windows 中使用 memmem() 的实现时遇到问题

c - 从 fgets() 输入中删除换行符

c - 数组到变量

c - 打开并解析文件

c - 关于在 Objective-c 堆上分配 c 结构和数组所需的指南

c - 嵌套结构的不完全类型结构问题

c - 打印函数变量时打印输出不同

c - strcpy:在 union 中使用 char** 变量作为参数