开发者

Alternative of struct tm

Does there exist any other alternative data structure instead of struct tm (having same memory allocated as this structure) ? So that I could use strftime without declaring <time.h>

I am aware of the fact that relying on implicit declaration is not good,but I fa开发者_JAVA技巧ced this question in an interview.

EDIT: To be precise I was asked to print the month for a corresponding integer using standard library function,but not allowed to include any header file.


No, you need to use time.h include file.

However, if you really want to use strftime and compile without errors or warnings, you could redefine the struct data type in your C file, and also the function prototype to use without including that file. You could call your struct type a different name as long as it matches up with the one currently in your time.h file.


The only thoughts I have are either the interviewer expected printing month strings, ignoring locale using your own const char array of month names, or one of those ill-defined "interactive" questions where you are suppose to stop and keep asking questions to clarify what the interviewer actually wants. Explicitly you want to express that you want to know what type of answer the interviewer is looking for. For example, just a short code fragment, ignoring details like error-checking and locale or reentrant issues, or an answer for some non-standard embedded or legacy environment, looking for another Standard C Library functions (ctime??), or a platform/OS specific answer?

ObCode:

const char* months[] = { "Jan", "Feb", ..., "Dec" };
...
printf("Month: %s\n", months[i]);

Or if a wildly "lateral thinker" on a Unix/Linux system:

char str[PATH_MAX];
...
assert(i >= 0 && i < 12);
cmd = snprintf(cmd, sizeof(cmd), "cal %d 2010 | head -1", i);
FILE* pipe = popen(cmd);
fread(str, 1, sizeof(str), pipe);
printf("Month: %s\n", str);

Pure bad idea. :)


So long as you do not need to access members of struct tm you can simply use a forward declaration of it thus:

struct tm ;

But to use strftime() you'd also need a declaration of its prototype. You don't want to work anywhere where they think such dubious practices are useful.


Using a library function requires that you include a header file...

Printing out a month name - I'm assuming you are allowed stdio.h - is independant of whether or not you can use strftime.

#include <stdio.h>

const char * months[] = {
    "January",
    "February",
    "March",
    "April",
    "May",
    ...
    "December"
};

int main () {
    int i = 0;
    for (; i < 12; ++i)
        printf ("Month %d: %s\n", i + 1, months[i]);
    return 0;
}

I'm being exact about your edit. Using only an int you can print a month associated with it. But printing itself, as has been mentioned, requires an include of its own...

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜