Reputation: 6361
I'm trying to iterate through several structs that each contain a timeval struct. I want to be able to grab the first date and store it in the START_DATE global variable. I also want to save the date of the last struct iterated through. I'm doing this by saving the time every single iteration in the END_DATE char*.
The problem I'm having is that even though START_DATE = asctime(localtime(&curSec)); is only being called once, START_TIME is being overwritten each iteration of the loop.
Is there an issue with points here that anyone can point out? No pun intended.
//Global
char *START_DATE = NULL;
char *END_DATE = NULL;
int main(int argc, char *argv[]) {
//start while loop that gets a new header struct each loop
time_t curSec = (time_t)header->ts.tv_sec;
if (!START_DATE)
START_DATE = asctime(localtime(&curSec));
END_DATE = asctime(localtime(&curSec));
//end while loop
printf("Start Date: %s", START_DATE);
printf("End Date: %s", END_DATE);
}
Upvotes: 0
Views: 549
Reputation: 13160
See asctime reference:
The array which holds this string is statically allocated and shared by both the ctime and asctime functions. Each time either one of these functions is called the content of this array is overwritten.
asctime
always returns the same pointer, which is to an internal buffer that it holds, so START_DATE
and END_DATE
always point to the same thing.
So each time you call the function, the string that both START_DATE
and END_DATE
are pointing to is changed.
To get a copy of the string that does not get overwritten, you will need to allocate your own buffer and copy it over using strncpy
(or strcpy
if you decide to use malloc(strlen(START_DATE) + 1)
instead of char buf[1024]
or similar).
Upvotes: 2