Reputation: 4920
I have a
char** color;
I need to make a copy of the value of
*color;
Because I need to pass *color to a function but the value will be modified and I cannot have the original value to be modified.
How would you do that?
The whole code would look like this
Function1(char** color)
{
Function2(char * color);
return;
}
I have to mention that the pointers in function1 and 2 are used as a return value.
Upvotes: 0
Views: 267
Reputation: 123578
Assuming you don't have strdup()
available (it's not part of the standard library), you would do something like this:
#include <stdlib.h>
#include <string.h>
...
void function1(char **color)
{
char *colorDup = malloc(strlen(*color) + 1);
if (colorDup)
{
strcpy(colorDup, *color);
function2(colorDup);
/*
** do other stuff with now-modified colorDup here
*/
free(colorDup);
}
}
Upvotes: 0
Reputation: 4869
Version 1
functionTwo( const char* color )
{
//do what u want
}
functionOne( char** color )
{
functionTwo( *color );
}
or version two
functionTwo( const char* color )
{
//do what u want
}
functionOne( char** color )
{
char* cpMyPrecious = strdup( *color );
functionTwo( cpMyPrecious );
free( cpMyPreciuos );
}
hth
Mario
Upvotes: 1
Reputation: 3207
i would suggest using strncpy() for duplicating the value. the string you are pointing at is in the memory just once, making another pointer to it doesn't solve your problem.
Upvotes: 0