我想将从名为 NextUnit()
的函数中获取的数据“somebytes”写入名为“output.txt”的文件,但我编写的代码不起作用。当我打开文件时,它看起来不像我的“somebytes”。这是代码:
#include <stdio.h>
#include <string.h>
char* NextUnit()
{
char Unit[256];
strcpy(Unit,"somebytes");
return &Unit[0];
}
int main()
{
FILE *ourfile;
ourfile=fopen("output.txt","wb");
char* somedata;
somedata=NextUnit();
printf("%s\n",somedata);
fwrite(somedata,1,strlen(somedata),ourfile);
fclose(ourfile);
}
最佳答案
您正在从函数返回本地地址(也称为已释放堆栈地址)。一旦您调用下一个函数,它就会发生变化。
以太只是返回一个全局常量
const char* NextUnit() { return "somebytes"; }
或者将其复制到一个新的内存结构中,稍后您还需要释放它...
char* NextUnit()
{
char* newstr = new char[256];
strcpy(newstr,"somebytes");
return newstr;
}
// some code later
char* tmpstr = NextUnit();
// do writing stuff
// free memory
delete tmpstr;
关于c++ - 如何从函数中获取一 block 内存并将其写入文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1157094/