考虑以下几点:
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/