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

问题描述 投票:1回答:1

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

[我当时想获得原始字符串的长度,并使用malloc动态分配内存,以便仅将*org复制到**cpy可以,但是没有用。

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

我对此很陌生,所以如果看不到真正简单的东西,我会提前道歉。

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

    {
      int i = 0;
      while(org[i] != '\0'){
        ++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;
}
c pointers new-operator
1个回答
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;
}


0
投票
#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;
}
© www.soinside.com 2019 - 2024. All rights reserved.