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);
}
See asctime reference:
asctimealways returns the same pointer, which is to an internal buffer that it holds, soSTART_DATEandEND_DATEalways point to the same thing.So each time you call the function, the string that both
START_DATEandEND_DATEare 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(orstrcpyif you decide to usemalloc(strlen(START_DATE) + 1)instead ofchar buf[1024]or similar).