DogDog
DogDog

Reputation: 4920

Problem with pointers of pointer ** char

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

Answers (3)

John Bode
John Bode

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

Mario The Spoon
Mario The Spoon

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

Pyjong
Pyjong

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

Related Questions