By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
454,435 Members | 1,485 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 454,435 IT Pros & Developers. It's quick & easy.

Error - function returns address of local variable

P: 1
int main(void)
{
char brand[20];

printf("Enter brand: ");
brand = validatebrand();

}

char * validatebrand()
{
char brandName[20];
.....
.......
......
if( (strlen (brandName)) >= 1 && (strlen (brandName)) < 20)
{
return brandName; <-- this is the warning
}
else
{
return NULL;
}
}

Ask user to key in brand, and use a validatebrand() to check whether it's valid or not, if it is valid, return the brandName. But when it is return, and i tried a printf to check what's returned in the main(), i found out tat it's not returned the exact data but the address. How i am going to make the validatebrand() to return the entire valid data after validated? Can anyone point it out?
Thanks
May 27 '07 #1
Share this Question
Share on Google+
1 Reply


weaknessforcats
Expert Mod 5K+
P: 9,197
Your problem is here:

Expand|Select|Wrap|Line Numbers
  1. char * validatebrand()
  2. {
  3. char brandName[20]; 
  4.  
brandName is an array local to validatebrand(). When validatebrand returns, the brandName array is destroyed. By returning the address of an array that is destoyed, youget the warning.

Your solution is to pass in the array from main(). That would be the
Expand|Select|Wrap|Line Numbers
  1. char brand[20];
  2.  
So you need to change validatebrand() to:

Expand|Select|Wrap|Line Numbers
  1. void validatebrand(char* brandName)
  2. {
  3. etc...
  4.  
May 27 '07 #2

Post your reply

Sign in to post your reply or Sign up for a free account.