C - 作为 return 值的结构不适合

C - struct as a return value does not fit

当我编译我的程序时,我收到一条错误消息: "incompatible types when assigning to type 'struct timeStamp *' from type 'struct timeStamp'"

我不知道出了什么问题... 可能是struct in struct的问题?

非常感谢您的帮助! THX - 亲切的问候!

这是我的垃圾代码...

结构声明:

struct timeStamp {
   int year;
   int mon;
   int day;
   int hour;
   int min;
};

struct weatherData {
   float temp;
   float hum;
   int lum;
   int wind;
   struct timeStamp *weatherStamp;
   struct weatherData *pN;
};

函数 timeManipulate 应该 return 一个结构:

struct timeStamp timeManipulate(struct tm *timeinfo) {
    timeinfo->tm_min -= 10;
    mktime(timeinfo);

    struct timeStamp *tS = NULL;
    tS = (struct timeStamp*)malloc(sizeof(struct timeStamp));
    if (tS==NULL)
        perror("Allocation Error");

    tS->year = (timeinfo->tm_year)+1900;
    tS->mon = (timeinfo->tm_mon)+1;
    tS->day = timeinfo->tm_mday;
    tS->hour = timeinfo->tm_hour;
    tS->min = timeinfo->tm_min;
    return *tS;
};

in main() 我想将由 "timeManipulate" 编辑的结构 return 分配给另一个结构:

struct weatherData *pNew = NULL;
pNew->weatherStamp = timeManipulate(timeinfo);

你的函数应该return一个指针

struct timeStamp *timeManipulate(struct tm *timeinfo)
/*               ^ make the function return a struct tiemStamp pointer */

并且 return 值应该是

return tS;

还有,你的

if (ts == NULL)
    perror("Allocation Error");

仍将取消引用 NULL 指针,它应该类似于

if (ts == NULL)
{
    perror("Allocation Error");
    return NULL;
}

这当然行不通

struct weatherData *pNew = NULL;
pNew->weatherStamp = timeManipulate(timeinfo);

你也必须为 pNew 分配 space。

最后不要转换 malloc() 不需要的结果。