[英]Returning a local pointer in C
const char* returnStr()
{
char time[40] = {"France"};
char* time1;
time1 = time;
return time1;
}
int main(int argc, char* argv[]) {
printf ("return String is %s\n",returnStr());
}
This code returns some junk characters. 此代码返回一些垃圾字符。 Won't the
const char*
not enough to return the local char pointer? const char*
是否不足以返回本地char指针? Do I have to use the static too in the function? 我也必须在函数中使用静态方法吗?
Do I have to use the static too in the function?
我也必须在函数中使用静态方法吗?
Yes. 是。 The
const
is just a qualifier on the return value, signaling to callers of returnStr
that they shouldn't modify the result of the function. const
只是返回值的限定符,向returnStr
调用者returnStr
信号, returnStr
他们不应修改函数的结果。 It doesn't change time
's temporary character. 它不会更改
time
的临时字符。
When the returnStr function terminates, its stack frame is deallocated - so whatever any local pointers point to is now random data. 当returnStr函数终止时,将释放其堆栈帧-因此,任何本地指针指向的内容现在都是随机数据。 If you want to return a pointer, you have to allocate it on the heap, with malloc for example.
如果要返回指针,则必须在堆上分配指针,例如malloc。
The time
object will exists only until returnStr
is running. time
对象将仅存在,直到returnStr
运行。 Once it returns to the function that called it, it is gone, and any pointer to it is invalid. 一旦返回调用它的函数,它就消失了,指向它的任何指针都是无效的。 In short, in C you cannot return an array from a function, you can only return a pointer to one.
简而言之,在C语言中,您无法从函数返回数组,只能返回指向一个数组的指针。 This is why standard library C functions do not allocate strings at all, you must pass in a string and specify how large it is and it will fill it or error out.
这就是为什么标准库C函数根本不分配字符串的原因,您必须传递一个字符串并指定它的大小,它将填充它或出错。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.