Return a string passed as an argument to a function

-1

I have this code and the problem is that it only prints me one h

  

Code

#include <stdio.h>

char imprimir_cadena(const char *cadena2);

int main(){

   const char *ptr="hola";

   const char *p=imprimir_cadena(ptr);

   printf("%s",&p);

   return 0;

}

char imprimir_cadena(const char *cadena2){

    return *cadena2; //el asterico * es opcional?


}
    
asked by eduu15 08.04.2018 в 21:34
source

2 answers

0

Because you are showing the value pointed by the pointer, the first character of your string in this case.

You should iterate over the string until p points to 0, which is the value with which it ends the C chains.

    
answered by 08.04.2018 в 22:52
0

Thanks to MAFUS for helping me with my doubts in this wonderful language
Here I leave the answer of MAFUS, I hope someone serves him

#include <stdio.h>

char* imprimir_cadena(const char *cadena2);

int main(){
    const char *ptr="hola";
    const char *p=imprimir_cadena(ptr);
    printf("%s", p); // cuando se imprimen cadenas no se usa asterisco
    return 0;
}

char* imprimir_cadena(const char *cadena2){ // nota que el tipo de dato devuelto es char*
    return cadena2; //el asterico * es opcional? No, no debe estar
}
    
answered by 09.04.2018 в 01:59