tags:

views:

94

answers:

4

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.

A: 

You can call strdup() to duplicate the string in *color, but you'll have to free() the result when you're done using it.

Function1(char **color)
{
    char *new_color = strdup(*color);
    Function2(new_color);
    // Maybe do something with new_color?
    free(new_color);
}
Frédéric Hamidi
A: 

hi.. 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.

stupid_idiot
+1  A: 

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

Mario The Spoon
I don't think that works if I need to modify it in the function 2.
Apoc
Then you go with version 2, drop the const from fucntionTwo, and do not free the cpMyPresious . Use it as you think - and once you are done, free it!
Mario The Spoon
A: 

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);
  }
}
John Bode