简体   繁体   English

指针** char的指针问题

[英]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. 因为我需要将* color传递给函数,但是该值将被修改,并且无法修改原始值。

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. 我不得不提到函数1和2中的指针用作返回值。

Version 1 版本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 hth

Mario 马里奥

i would suggest using strncpy() for duplicating the value. 我建议使用strncpy()复制值。 the string you are pointing at is in the memory just once, making another pointer to it doesn't solve your problem. 您指向的字符串仅在内存中存在一次,因此再指向该字符串不能解决您的问题。

Assuming you don't have strdup() available (it's not part of the standard library), you would do something like this: 假设您没有可用的strdup() (它不是标准库的一部分),则可以执行以下操作:

#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);
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM