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..
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
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
>> 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);
}
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.
ASKER
give me a minute to try it out..
ASKER
Perfect! Quick and precise!
May god bless you and never let your machine crash!
Thanx a lot,
Nick
May god bless you and never let your machine crash!
Thanx a lot,
Nick
ASKER
I just though that this is a more active area...