Search code examples
cpointersnew-operator

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


I want to copy a const string const char * org to char **cpy, but my code doesn't work.

I was thinking getting the lenght of my original string and and using malloc to dynamically allocate memory, in order to just copy *org to **cpy would work, but it doesn't.

Where is my mistake? Cant't I use strcpy for a pointer to a pointer or how exactly do I do it?

I'm very new to this, so I appologize in advance if I don't see something really simple.

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

Solution

  • try this

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