Carlos Contreras Carlos Contreras - 13 days ago 7
C Question

Copy global char** in a new char**

char * seleccion[5]={" "," "," "," "," "};

char **armar_Equipazo() {
char** equipo= (char **)malloc(sizeof(seleccion));
for(int i =0 ; i<5 ; i++)
strcpy(equipo[i],seleccion[i]);
return equipo;
}


I need copy a char ** in a new "array", but my code do not succed because my malloc is wrong buy I do not know why.
Can you help me please ?

Answer

It depends on how you are going to copy. If you want to copy the elements of the array seleccion in a new array then you can write

char * seleccion[5] = { "  ", "  ", "  ", "  ", " " };

char ** armar_Equipazo() 
{
    char **equipo = ( char **)malloc( sizeof( seleccion ) );

    memcpy( equipo, seleccion, sizeof( seleccion ) );

    return equipo;
}

If you want to make copies of the strings pointed to by the elements of the array seleccion then you should write

char * seleccion[5] = { "  ", "  ", "  ", "  ", " " };

char ** armar_Equipazo() 
{
    char **equipo = ( char **)malloc( sizeof( seleccion ) );

    for( size_t i = 0; i < sizeof( seleccion  / sizeof( *seleccion ); i++ )
    {
        equipo[i]  = malloc( strlen( seleccion[i] ) + 1 );
        strcpy( equipo[i], seleccion[i] );
    }

    return equipo;
}