-
System Time
I tried writing a function that returns just the time. It doesn't work, it gives really weird characters:
Code:
char* GetTime()
{
bool flag=false;
time_t now;
time(&now);
char* time = new char[10];
char* realtime = new char[10];
strcpy(time, ctime(&now));
for(int x=0; x<10; x++)
{
if(!flag)
{
if(time[x] == ':')
{
wsprintf(realtime, "%c%c%c%c%c", time[x-2], time[x-1], time[x], time[x+1],
time[x+2]);
flag = true;
}
}
}
return realtime;
}
any idea whats wrong?
-
A few things:
1) You allocate only 10 characters for the return from ctime. Ctime will return a string that is something like "Fri May 23 19:36:40 2003" which is longer than 10 characters, so you overfill your buffers.
2) As unusual as your character searching is, it works. However, it would be much easier to use:
Code:
int x = strcspn(time,":");
and then, time[x] would be the location of the first ':'.
3) A big problem is your return. You're returning the address of the buffer, but the buffer is out of scope as soon as the function ends -- i.e. you're returning an address to a buffer that won't exist when the other function gets it. It might work (as the data might still be there) but it is by no means guaranteed.
To that end, you should do this:
Code:
char * realtime = new char[6]; // 6 bytes is enough for 5 chars + null termination
.
.
.
return realtime;
And then, whenever you call the function, after you are done with the string it returned, free it with delete[] .
Code:
for (int i = 0; i < 10; i++){
char * t = GetTime();
printf("The time is %s",t);
delete[] t;
}
-
the string returned by ctime is 26 char long, therefore when you try to copy the 26 char into a 10 char array, you got troubles.
if x == 0; then time[x - 2] and time[x - 1] are undefined as indexes cannot be negative values.
try not to use variables the same name as functions. it can get very confusing.
well, looks like I'm wrong about the indexes. Now that I read Cat's post I can see my error.
On the other hand, realtime was declared with dynamic memory in the version I saw.