c++ - Printing output from string building function not returning expected result -


i'm writing function output basic hours & minutes string in 24 hour format 2 global int's containing hours , minutes.

i've defined these during initialization:

int g_alarmhours = 7; int g_alarmminutes = 0; 

the function return string is:

char* getalarmtime() {   int hours = g_alarmhours;   int minutes = g_alarmminutes;   char t[6];   t[0] = (hours/10) + '0';   t[1] = (hours%10) + '0';   t[2] = ':';   t[3] = (minutes/10) + '0';   t[4] = (minutes%10) + '0';   t[5] = 0;   return t; } 

the global variables stubs replaced when serial comms device added values retrieved from.

calling function generates following hex values @ character pointer:

0x20 0x4b 0x00 

when replace top 2 lines of getalarmtime() function following

int hours = 7; int minutes = 0; 

the output expect, of:

07:00\0 

why using global variables causing output of getalarmtime() go wonky?

you returning pointer local variable on stack. memory pointer pointing @ no longer valid , accessing memory invokes undefined behavior. reason why seeing such strange behavior because can happen when invoke undefined behavior.

the solution problem code in c++ , use std::string.

std::string t; t.push_back((hours/10) + '0'); ...  return t; 

Comments

Popular posts from this blog

Unable to remove the www from url on https using .htaccess -