Returning memory location?
Sep 27, 2009 at 12:00am UTC
Hello,
How do I return a memory location from a member function of a class? Any assistance will be really appreciated.
1 2 3 4 5 6 7 8 9 10
char *ClassName::memberFunctionName(const int &info)
{
NodeType *current;
static char address;
address = ¤t;
return address;
}
Sep 27, 2009 at 12:02am UTC
That is a dangerous thing to do. What are you trying to accomplish?
Sep 27, 2009 at 12:21am UTC
I am trying to create a member function of a class that searches a linked list for a particular value, and when it finds that value, it returns the address of the node where the info is stored. Here is an example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
char *ClassName::memberFunctionName(const int &info)
{
ClassName *current;
static char [10] address;
bool found = false ;
current = head; // head is defined in the header file
while (current->info != NULL && !found)
{
if (current->info == info)
{
found = true ;
}
else
current = current->next;
}
address = ¤t;
if (found)
return address;
else
return NULL;
}
Sep 27, 2009 at 1:36am UTC
I think you are a little confused on how pointers work. You might want to take a read through the tutorial section of this site.
Don't use static values. Just return the found current address.
1 2 3 4 5 6
while (current != NULL)
{
if (current->info == info) break ;
current = current->next;
}
return current;
Good luck!
Sep 27, 2009 at 2:27am UTC
Your right Duoas. So Ive redone it and it now works. Thanks
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
ClassName *ClassName::memberFunctionName(const int &info)
{
ClassName *current;
//static char [10] address;
bool found = false ;
current = head; // head is defined in the header file
while (current->info != NULL && !found)
{
if (current->info == info)
{
found = true ;
}
else
current = current->next;
}
//address = ¤t;
if (found)
return current;
else
return NULL;
}
Sep 27, 2009 at 5:12am UTC
Glad to have been of help. :-)
Topic archived. No new replies allowed.