#include <stdio.h>
#include <string.h>
FILE * BestTry();
int main()
{
char arr[] = "hello";
FILE * desc = BestTry();
fwrite(arr,1,5,desc);
fclose(desc);
}
FILE * BestTry()
{
FILE * retDesc = fopen(".\\hello.dat","w+");
return retDesc;
}
Run Code Online (Sandbox Code Playgroud)
是否可以安全地desc用于任何用途,因为我正在为函数中的局部变量分配内存BestTry.如果它是安全的那么原因是什么?
该FILE对象不是您的BestTry函数的本地对象.该函数获取指向FILE对象的指针,该指针确实是本地的,但对象本身不是.
你正在做的很好,FILE当你返回指针时,实际的对象仍然存在.(好吧,除非您没有检查系统调用的返回值,因此在失败时调试程序会非常困难.)