Hi.. if I use the Serial.println(vbuffer_Saida_geral).. It prints perfectly, but when I return the value it doesn't return correctly.. just some weird characters.
void setup()
{
Serial.begin(9600);
}
char *completar_com_zeros(byte numero, int zeros)
{
char vsaida[6] = "";
char vbuffer_Saida_geral[20];
char vinicio_dos_parametros[3] = "%0";
char vbuffer_zeros_para_inserir[4];
sprintf(vbuffer_zeros_para_inserir, "%01i", zeros); // converte o numero int para a string com nome de buffer_zero e inserindo 'zeros'
strcat(vsaida, vinicio_dos_parametros);
strcat(vsaida, vbuffer_zeros_para_inserir);
strcat(vsaida, "d");//insere o parametro 'd' no final da string vsaida
sprintf(vbuffer_Saida_geral, vsaida, numero);
return(vbuffer_Saida_geral);
}
void loop()
{
int total_zeros = 4;
int vvalor = 56;
Serial.println(completar_com_zeros(vvalor, total_zeros));
//Serial.println(vsaida);
delay(1000);
}
Something related to convert vbuffer_Saida_geral which is 20 sized to the *completar_com_zeros from the function?
You have declared vbuffer_Saida_geral inside the function. It does not exist once the function returns.
One way to fix this is to make vbuffer_Saida_geral a global array.
el_supremo:
You have declared vbuffer_Saida_geral inside the function. It does not exist once the function returns.
One way to fix this is to make vbuffer_Saida_geral a global array.
Pete
Just change to static and worked fine!
Could you explain, why changing to static works?
Also, if I can print inside the function its because value is there(isn't it?). but why when I return it, the value goes away?
If it is local to the function, the array is allocated on the stack when the function starts. When you return from the function, what was on the stack is no longer valid.
For more details, have a look for "scope of variables in C++"
el_supremo:
For more details, have a look for "scope of variables in C++"
Pete
Actually, scope does not matter here, but the lifetime. The scope is exactly the same between the static and auto variables declared/defined in the function.