简体   繁体   English

函数return char []代替int

[英]Function return char[] instead of int

I need some help with my C function. 我的C函数需要一些帮助。 I'm trying to get the current CPU time and return it as a char[] for use later on. 我正在尝试获取当前的CPU时间,并将其作为char []返回,以便以后使用。 The problem that I'm getting is that I don't have my pointers/dereferences in the right place and I'm getting compiler warnings/errors. 我遇到的问题是我的指针/取消引用的位置不正确,并且我收到了编译器警告/错误。 What changes do I need to make to get this to work correctly? 我需要进行哪些更改才能使其正常工作?

Function: 功能:

char *get_time()
{
    char time_char[10];
    time_t rawtime;
    struct tm * timeinfo;

    time ( &rawtime );
    timeinfo = localtime ( &rawtime );
    int time = timeinfo->tm_yday*1000000 + timeinfo->tm_hour*10000 + timeinfo->tm_min*100 + timeinfo->tm_sec;

    sprintf(time_char, "%d", time);
    return *time_char;
}

Calling function with char time_char[] = get_time(); char time_char[] = get_time();调用函数

What I had before I moved the code to a function and worked as I needed it to was this: 在将代码移至函数并按需要工作之前,我所拥有的是:

char time_char[10];
time_t rawtime;
struct tm * timeinfo;

time ( &rawtime );
timeinfo = localtime ( &rawtime );
int time = timeinfo->tm_yday*1000000 + timeinfo->tm_hour*10000 + timeinfo->tm_min*100 + timeinfo->tm_sec;

sprintf(time_char, "%d", time);

And then I used time_char as needed. 然后根据需要使用time_char

The array is allocated in the function's call-frame and is deallocated when the function returns. 数组在函数的调用框架中分配,并在函数返回时释放。

You'll either need to pass-in the array by pointer (as keltar comments) in which case you don't need to return anything and the function can be marked void , or allocate memory with malloc and return the pointer. 您可能需要通过指针传递数组(如keltar注释),在这种情况下,您无需返回任何内容,并且可以将函数标记为void ,或者使用malloc分配内存并返回指针。

Change your prototype to: 将您的原型更改为:

char *get_time(char *time);

Allocate the appropriate memory to time in the calling function , then call free(time); 调用函数中time分配适当的内存,然后调用free(time); when you are done using it (also from the calling function). 使用完后(也可以通过调用函数)。

Also, your return statement should simply be: 同样,您的return语句应该只是:

return time;

First, you can't return a pointer to an automatic local variable. 首先,您不能返回指向自动局部变量的指针。 Second, to return a pointer you do not need a dereference operator. 其次,要返回指针,您不需要解引用运算符。

Although in general this is not advisable, sometimes it is useful to return a character array, as follows: 尽管通常不建议这样做,但有时返回一个字符数组很有用,如下所示:

typedef struct char10 {char str[10];} char10;

char10 get_time() {
    char10 time_char;
    // ...
    sprintf(time_char.str, "%d", time);
    return time_char;
}

One downside is that, for example, gcc gives an unnecessary warning message for code such as: 不利的一面是,例如, gcc为诸如以下代码提供了不必要的警告消息:

    printf("%s\n", get_time().str);

which you can avoid via the ugly: 您可以通过丑陋的方式避免这种情况:

    printf("%s\n", &get_time().str[0]);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM