Link to home
Start Free TrialLog in
Avatar of anemos
anemos

asked on

pointer arguments

I have declared the following variable:

char * previous;

 I have allocated space for one chat to it:

previous = malloc(1);

I have initialized it as:

previous="\0";

I want to pass it to a function that will change its size using malloc and change its contents by copying another string to it:
                   strcpy(previous,curr);

 Now when I've returned from the function previous should be containing the string.

How am I going to pass the pointer to this function in order to achieve this???

I hope you all understand what I mean..
Thanx in advance..
ASKER CERTIFIED SOLUTION
Avatar of KangaRoo
KangaRoo

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of anemos
anemos

ASKER

ooops! sorry for moving!
I just though that this is a more active area...
>> previous = malloc(1);
Better use new:
prev = new char[1];

>> previous="\0";

You've changed the pointer, not the contents of the previously allocated memory.
Might have wanted to do:

*previous = '\0';

You need to pass the pointer in a way that allows the function to change it, so pass the pointer by reference:

void change(char*& p)
{
   char* str = "hello";
   delete [] p;
   p = new char[strlen(str) + 1];
   strcpy(p, str);
}




Never mind, such a thing rarely happens.
Avatar of anemos

ASKER

give me a minute to try it out..
Avatar of anemos

ASKER

Perfect! Quick and precise!
May god bless you and never let your machine crash!
 Thanx a lot,

 Nick