Reputation: 1
#include<iostream>
using namespace std;
struct sample
{
int data[3][2];
};
struct sample* function()
{
struct sample s;
int c=1;
for(int i=0;i<3;i++)
for(int j=0;j<2;j++)
s.data[i][j]=c++;
cout<<"Matrix contents are ";
for(int i=0;i<3;i++)
{
for(int j=0;j<2;j++)
cout<<s.data[i][j])<<"\t";
cout<<"\n";
}
return &s;
}
int main()
{
struct sample *ss;
ss=function();
cout<<"Matrix contents are ";
for(int i=0;i<3;i++)
{
for(int j=0;j<2;j++)
cout<<ss->data[i][j]))<<"\t";
cout<<"\n";
}
return 0;
}
What is the error here? When I display content in that function it is getting output, but when I try to display contents outside of the function it displays garbage. What is wrong?
Upvotes: 0
Views: 1254
Reputation: 8529
Variable s is local the function ==> it will get destroyed when function returns since local variable have auto storage type and life time is limited to scope in which they are defined.
You can change storage type of variable s to static, static variables life time is whole program so you can return reference of it.
Upvotes: 0
Reputation: 258288
Your s
variable is allocated on the stack, and then you are returning a pointer to it; however, when the function ends, s
no longer exists and the pointer is no longer valid.
You could either dynamically allocate s
and return a reference/pointer to it, or you could return a copy of s
rather than a reference.
In other words, you have a case of a dangling pointer.
Upvotes: 6