I am supposed to test the runtime of some algorithms with diffrent complexities as a function of m. Given some values for m, I need to change m to a "clock" format you know day hr : min : sec : msec.
Here's the code for conversion:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
string format(int m)
{
int ms;
int ss;
int mm;
int dd;
int hh;
ms = m%1000;
m = (m - ms)/1000;
ss = m%60;
m = (m - ss)/60;
mm = m%60;
m = (m - mm)/60;
hh = m%24;
dd = (m - hh)/24;
char * charr;
sprintf(charr, "%03d %02d:%02d:%02d:%02d", dd, hh, mm, ss, ms);
return charr;
}
Now I'm inputing the runtime in a text file, using the following code:
It should have crashed on Windows, also. (You are just lucky that it didn't.)
Line 16 only allocates a pointer variable -- the pointer does not point to anything in particular. The crash likely occurs on line 17 when you try to sprintf() to some random memory location.
I do have to wonder why you are using sprintf() at all. Why not use the C++ way?
string format(int m)
{
int ms = m%1000; m /= 1000;
int ss = m%60; m /= 60;
int mm = m%60; m /= 60;
int hh = m%24; m /= 24;
int dd = m;
ostringstream result;
result << setfill( '0' )
<< setw( 3 ) << dd << " "
<< setw( 2 ) << hh << ":"
<< setw( 2 ) << mm << ":"
<< setw( 2 ) << ss << ":"
<< setw( 2 ) << ms;
return result.str();
}
That said, if you must, change your line 16 to read
16char charr[ 17 ];
That will be implicitly-constructed into a string when you return it.