[SOLVED] How to retun an Array to a function?

Status
Not open for further replies.

agg_mayur

Member level 3
Joined
Feb 25, 2010
Messages
66
Helped
3
Reputation
6
Reaction score
3
Trophy points
1,288
Location
India
Activity points
1,715
Dear All,

Please tell me how to retun an array to a function. For e.g. i want to print Name

class office{
char name[4];
int emp;
public:
void set_name(char *n);
char get_name();
void set_emp(int e);
int get_emp();
};
void Office::set_name(char *n)
{
memcpy(&name,n,4); //Is it right
}
void Office::set_emp(int e)
{
emp = e;
}
char Office::get_name()
{
return *name; //How to return whole array to a function//wants modification
}
int Office::get_emp()
{
return emp;
}
int main()
{
char n[4] = "ABC";
Office o;
o.set_name;
o.set_emp(457);
cout << "Company Name is " << o.get_name();
cout << "\n"; cout << "\n";
cout << "No. of Employees are " << o.get_emp();
cout << "\n";
return 0;
}
 

return a pointer to (the address of) name[], e.g.
Code:
char * Office::get_name()
{
return name; //How to return whole array to a function//wants modification
}
 

Re: How to return an Array to a function?

return a pointer to (the address of) name[], e.g.
Code:
char * Office::get_name()
{
return name; //How to return whole array to a function//wants modification
}

Thanks for the reply, it works. Is there any harm to return an local array?
Also please describe me how it works(above solution)?
 

you were returning a pointer to a global array which is OK.
do not return pointers to variables or local arrays, e.g.
Code:
char * get_name()
{
    char name[20]="joe";
    return name;
}
local variables are allocated on the stack on entry to the function and lost on exit therefore using such a returned pointer would destroy the stack integrity
given the above code the gcc compiler gives a warning
Code:
c1.cpp|3|warning: address of local variable 'name' returned|
 
Reactions: agg_mayur

    agg_mayur

    Points: 2
    Helpful Answer Positive Rating

    KMS17

    Points: 2
    Helpful Answer Positive Rating
Status
Not open for further replies.
Cookies are required to use this site. You must accept them to continue using the site. Learn more…