C / 使用动态 malloc 复制字符串,从 const char * org 到 char ** cpy

C / Copy String with dynamic malloc, from const char * org to char ** cpy

我想将常量字符串 const char * org 复制到 char **cpy,但我的代码不起作用。

我正在考虑获取原始字符串的长度并使用 malloc 动态分配内存,以便仅将 *org 复制到 **cpy 就可以了,但它不起作用't.

我的错误在哪里?我不能将 strcpy 用作指向指针的指针,或者我该怎么做?

我对此很陌生,所以如果我没有看到非常简单的东西,我会提前道歉。

int string_dd_copy(char **cpy, const char * org)

    {
      int i = 0;
      while(org[i] != '[=10=]'){
        ++i;
      }
      if(i == 0){
        return 0;
      }
      *cpy = malloc(i* sizeof(char));
      strcpy(*cpy, org);
      printf("%s", *cpy);

      return 1;
    }

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(void)
{
int string_dd_copy();
char **a;
char *b = "Iam";
string_dd_copy(a, b);
return 0;
}

int string_dd_copy(char **cpy, const char * org)
{
  cpy = malloc(1 + strlen(org));
  strcpy(*cpy, org);
  return 1;
}

试试这个

#include <stdio.h>
#include <string.h>
#include <malloc.h>
int string_dd_copy( char **cpy, const char *org )
{
    if( strlen(org)  == 0 ){
        printf( "no data\n");
        return 0;
    }

    *cpy = malloc( strlen( org ) + 1 );

    strcpy( *cpy, org );

    printf("%s\n", *cpy);

      return 1;
}
int main()
{

    const char *teststring = "hello world";
    const char *noData = "";

    char *testptr;
    string_dd_copy( &testptr, teststring );
    free( testptr );

    string_dd_copy( &testptr, noData );
    return 0;
}