所以我有一个文件,作为一些文本,我希望我的函数读取该文件并将其存储在一个数组上。我做了一些代码,当我打印我的动态数组时,它会打印垃圾值:<帮助。C语言 - >读取文件到动态数组
char* read_message(char *filename)
{ //gets the PATH of the txt file
char *file_contents;
long input_file_size;
FILE *input_file = fopen(filename, "r");
if(input_file == NULL)
{
return NULL;
}
fseek(input_file, 0, SEEK_END);
input_file_size = ftell(input_file);
rewind(input_file);
file_contents = (char*)malloc(input_file_size+1 * (sizeof(char)));
fread(file_contents, input_file_size, 1, input_file);
printf("%s",file_contents);//----Prints crap--------
fclose(input_file);
// returns the address to the array of strings
return file_contents;
}
请在此处发布您的代码,而不是代码的图像。 – AntonH
请将代码作为文本发布,而不是文本图片或文本图片的链接。同时发布您的输入,预期输出和实际输出。 – dbush
只是好奇:你为什么分配'input_file_size + 1'? ''最后'+ 1'是最基本的(请参阅@dbush [answer](https://stackoverflow.com/a/47359654/2436175)),但我想知道你是怎么想出来的,如果你没有了解终止角色。 – Antonio