Your program has very serious problems, it is rare that it even works in a harmless way.
Variables used outside its scope .
In the function trocear
you create the variable salida
of pointer type to character char *
and you return that pointer, which, since it belongs to the function trocear
when you leave this function, it ceases to exist and misses. Using the values of a variable that has ceased to exist is a undefined behavior .
Poorly used pointer arithmetic .
The variable salida
is a pointer that does not point to any existing data. The pointers exist to point to data (read this thread ) and only when they point to something do they make sense. In your case, you create the pointer but do not assign it value:
char *salida;
This implies that it points to an unknown place in the memory (uninitialized variables receive an indeterminate value when created), from that unknown place you do arithmetic pointers to point to different points starting from an unknown origin:
*(salida+i)=num%10+'0';
This line is translated as: " From the point where you are, it advances i
positions and at that point it writes the indicated value ", the problem is that without knowing the point from the that you start, you will hardly know the point at which you are going ... this is another indefinite behavior.
Proposal.
If you want to work with pointers (I would not do it, but if it is a requirement we will need to stick to it), you will need to use dynamic memory instead of automatic memory (automatic memory is released when leaving the area in which it is created, the dynamic memory is released by hand) so your trocear
function should look like this:
char * trocear(int num) {
// Un entero de 32 bits puede contener números de hasta 10 dígitos
char *salida = new char[11];
// hacer cosas...
return salida;
}
With this proposal, the memory you created in trocear
should be released after use:
char *n = trocear(123456);
cout << n;
delete[] n; // <---- MUY IMPORTANTE
But doing this is a major headache, I advise you to use smart pointers:
std::unique_ptr<char[]> trocear(int num) {
// Un entero de 32 bits puede contener números de hasta 10 dígitos
auto salida = std::make_unique<char[]>(11);
for (int digito = 0; num; ++digito)
{
salida[digito] = '0' + num % 10;
num /= 10;
}
return salida;
}
The smart pointer will take care of releasing the memory at the end of its use, freeing you from the responsibility of doing it by hand:
auto n = trocear(123456);
cout << n.get();
You can see the code working in Wandbox .