0

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.

DogDog
  • 4,820
  • 12
  • 44
  • 66

3 Answers3

1

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
  • 4,799
  • 1
  • 24
  • 36
0

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.

Pyjong
  • 3,095
  • 4
  • 32
  • 50
0

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
  • 119,563
  • 19
  • 122
  • 198