Continue to Site

Welcome to EDAboard.com

Welcome to our site! EDAboard.com is an international Electronics Discussion Forum focused on EDA software, circuits, schematics, books, theory, papers, asic, pld, 8051, DSP, Network, RF, Analog Design, PCB, Service Manuals... and a whole lot more! To participate you need to register. Registration is free. Click here to register now.

[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(n);
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|
 
  • Like
Reactions: agg_mayur

    agg_mayur

    Points: 2
    Helpful Answer Positive Rating

    KMS17

    Points: 2
    Helpful Answer Positive Rating
Status
Not open for further replies.

Part and Inventory Search

Welcome to EDABoard.com

Sponsor

Back
Top