C在本地函数中返回FILE * [英] C return FILE * in local function

查看:61
本文介绍了C在本地函数中返回FILE *的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一段代码

Here is a piece of code

FILE *got_file(char *str)
{
   FILE *fp = fopen(str, "r");
   return fp;
}


这样可以吗我认为fp是指向存储在堆栈中的FILE结构的指针.这里有问题吗?

另一个:


will this be OK? the fp is a pointer points to FILE struct which stores in stack, I think. Any problems here?

Another one:

char *got_str1()
{
   static char *test = "a test";
   return test;
}


这样行吗?


will this OK?

static char *got_str2()
{
   char *test = "a test";
   return test;
}



这样行吗?



will this OK?

推荐答案

引用:

FILE * got_file(char * str)
{
FILE * fp = fopen(str,"r");
return fp;
}
这样可以吗我认为fp是指向存储在堆栈中的FILE结构的指针.这里有任何问题吗?

FILE *got_file(char *str)
{
FILE *fp = fopen(str, "r");
return fp;
}
will this be OK? the fp is a pointer points to FILE struct which stores in stack, I think. Any problems here?

可以. FILE结构在堆栈上不是(临时的),它的指针是(但是指针值,即将地址复制为返回值).

This is OK. The FILE struct is NOT (a temporary) on the stack, its pointer is (but the pointer value, that is the address is copied as return value).

报价:

char * got_str1()
{
static char * test =一个测试";
退货测试;
}

char *got_str1()
{
static char *test = "a test";
return test;
}


是的,可以,静态变量不是临时变量.



Yes, it is OK, static variables are not temporaries.


报价:

静态字符* got_str2()
{
char * test =一个测试";
退货测试;
}
这样行吗?

static char *got_str2()
{
char *test = "a test";
return test;
}
will this OK?


就目前而言,它很丑陋(如果您问我,我不会使用它),它应该也可以.因为字符串文字不是临时的.


Ugly as it stands (I won''t use it, if you ask me), it should be OK too. Because string literals are not temporaries.


这些还可以吗?
好吧,不,它们不是,可能会引起问题.

麻烦的是,正如您所说的,它们都是基于堆栈的变量.因此,当在最后声明它们的方法时,它们将超出范围.更糟糕的是,堆栈空间被回收,将由您调用的下一个函数使用.这些被称为悬空指针",而Wiki则比我更好地解释了它们: http://en.wikipedia.org/wiki/Dangling_pointer [^ ]

这样做不是一个好主意-它可以在以后很难发现问题时存储问题!
Are these ok?
Well, no, they aren''t, and will probably cause problems.

The hassle is that they are all stack based variables, as you have said. So when the method they are declared in ends, they go out of scope. Worse, the stack space is reclaimed, and will be used by the next function you call. These are called "dangling pointers" and wiki explains them better than I would: http://en.wikipedia.org/wiki/Dangling_pointer[^]

It isn''t a good idea to do this - it stores up problems for later when they are really difficult to spot!


这篇关于C在本地函数中返回FILE *的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆