通过指针在C和C ++函数返回的本地数据 [英] Returning local data from functions in C and C++ via pointer

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

问题描述

我和我的朋友的说法。他说,我可以从一个函数返回一个指针到本地数据。这不是我所学,但我无法找到反驳他,证明我的知识。

I have argument with my friend. He says that I can return a pointer to local data from a function. This is not what I have learned but I can't find a counterargument for him to prove my knowledge.

下面说明情况:

char *name() {
    char n[10] = "bodacydo!";
    return n;
}

和它的使用为:

int main() {
    char *n = name();
    printf("%s\n", n);
}

他说,这是完全可以的,因为程序调用名后,它返回一个指向n和之后,它只是打印了。没有什么事情发生在节目同时,因为它是单线程和执行是串行的。

He says this is perfectly OK because after a program calls name, it returns a pointer to n, and right after that it just prints it. Nothing else happens in the program meanwhile, because it's single threaded and execution is serial.

我找不到反驳的理由。我从来不写code这样的,但他很固执,并说这是完全确定。如果我是他的老板,我会解雇他是一个倔强的傻瓜,但我不能找到一个相反的观点。

I can't find a counter-argument. I would never write code like that, but he's stubborn and says this is completely ok. If I was his boss, I would fire him for being a stubborn idiot, but I can't find a counter argument.

另外一个例子:

int *number() {
    int n = 5;
    return &n;
}

int main() {
    int *a = number();
    int b = 9;
    int c = *a * b;
    printf("%d\n", c);
}

我会送他这个链接后,我得到一些很好的答案,所以他至少学到一些东西。

I will send him this link after I get some good answers, so he at least learns something.

推荐答案

你会得到一个问题,当你调用的名称()和printf()之间的另一个功能,它本身使用堆栈

you will get a problem, when you call another function between name() and printf(), which itself uses the stack

char *fun(char *what) {
   char res[10];
   strncpy(res, what, 9);
   return res;
}

main() {
  char *r1 = fun("bla");
  char *r2 = fun("blubber");
  printf("'%s' is bla and '%s' is blubber", r1, r2);
}

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

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