String 函数返回结构和函数返回字符串——不同的行为?

String 函数返回结构和函数返回字符串——不同的行为?,string,function,structure,local,String,Function,Structure,Local,我听说我们不能从函数返回指向本地(自动)数组变量的指针,因为自动变量的作用域有限,一旦被调用函数返回,它们就会消失 char *s getName() { char name[]="Sumit"; // Automatic variable retrun name; // No scope outside the function } 但我心中产生了一个疑问: struct info getInfo(int a,int b) { struct info f1; // Automatic

我听说我们不能从函数返回指向本地(自动)数组变量的指针,因为自动变量的作用域有限,一旦被调用函数返回,它们就会消失

char *s getName()
{
char name[]="Sumit";  // Automatic variable 
retrun name; // No scope outside the function

}
但我心中产生了一个疑问:

struct info getInfo(int a,int b)
{

struct info f1; // Automatic variable memory allocated for a structure
f1.a=a; 
f1.b=b;

return f1;

}
这里我们还返回一个对本地分配的内存位置的引用。那怎么会在这里工作得很好呢

PLZ帮助 等待回复

,因为您“实际上”返回了2个整数(不完全如此,但遵循类比)

原因也是一样

inline int GetZero (int i)
{
    int j = i;

    return j;
}

GetZero(0);
工作

此外,您不是在返回引用,而是在返回值

这是通过引用返回的:

int& GetZero (int i)
显然这是通过指针返回的:

int* GetZero (int i)

getInfo
如何返回指针?getInfo()不返回指针。它正在返回一个结构。我的问题是,为什么分配给字符串的内存会在函数返回后消失,而结构则相反,它会被保留并可用于调用函数。