通过指针从 C 和 C++ 中的函数返回本地数据 [英] Returning local data from functions in C and C++ via pointer
问题描述
我和朋友吵架了.他说我可以从函数返回一个指向本地数据的指针.这不是我学到的,但我找不到反驳他来证明我的知识.
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);
}
他说这完全没问题,因为在程序调用 name 后,它返回一个指向 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.
我找不到反驳的论点.我永远不会写那样的代码,但他很固执,说这完全没问题.如果我是他的老板,我会因为他是一个顽固的白痴而解雇他,但我找不到反驳.
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
", c);
}
在我得到一些好的答案后,我会把这个链接发给他,所以他至少学到了一些东西.
I will send him this link after I get some good answers, so he at least learns something.
推荐答案
你会遇到一个问题,当你在 name() 和 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屋!