New char in c ++ gives me long wrong

0

The question is why when I do

char *ic( char *p ) {
  int largo = strlen( p );
  char *retorno = new char[largo]( )
}

Being the length of the char p = 4, I think long return 14

    
asked by JKnaps 18.04.2017 в 00:57
source

1 answer

1

I'm assuming that when you pass the pointer to your function you are declaring an array and you did not finish it by specifying the null character example

int main()
{
    char arr[]={'a','b','c','d'};
    ic(arr);
    return 0;
}

Therefore the strlen function does not properly calculate the size of the pointer to char because it does not find the null character that indicates the end of the string.

The way to correct it is obviously adding the null character

 char arr[]={'a','b','c','d','
int main()
{
    char arr[]={'a','b','c','d'};
    ic(arr);
    return 0;
}
'};
    
answered by 18.04.2017 / 06:31
source