[Techtalk] getting the time as a string in c
Dan
dan at cellectivity.com
Thu Sep 29 05:33:02 EST 2005
> int timestrsize = 10; /* max length of time string */
> char *timestring;
> char timeformat[2] = "%c"; /* format for time string */
> const struct tm *timeptr;
>
> size_t strftime(timestring, timestrsize, timeformat, timeptr);
Is that your whole main()? Did you notice that "timestring" is never
initialised?
Also, note that "timeformat" is defined to have length 2, but it has to
have length 3 because all strings in C are null-terminated. (The length
isn't stored; the end is signaled by '\0').
> I have absolutely no idea what "const struct tm *timeptr" is doing...
> the rest of it I think I understand at least somewhat.
The answer is in "man ctime". Briefly put, "strftime" doesn't format the
current time only; it accepts a time that you pass in.
> I think before I had "char timestring[10];" instead of "char
> *timestring;". When that was the case, gcc didn't complain and the
> program compiled, but running it produced a segmentation fault.
I would think it would be the opposite: "char timestring[10];" is at
least initialised and so doesn't lead to pointer worries. "char
*timestring" is an uninitialised pointer.
--
I'm an idiot. At least this one [bug] took about 5 minutes to find.
- attributed to Linus Torvalds
More information about the Techtalk
mailing list