C-struct作为返回值不适合
当我编译我的程序时,我得到一个错误,告诉我: “从类型‘struct timeStamp’分配给类型‘struct timeStamp*’时,类型不兼容” 我不知道怎么了。。。 也许是struct中的struct有问题 非常感谢你的帮助! THX-亲切的问候 这是我的垃圾代码 结构声明:C-struct作为返回值不适合,c,struct,return-value,C,Struct,Return Value,当我编译我的程序时,我得到一个错误,告诉我: “从类型‘struct timeStamp’分配给类型‘struct timeStamp*’时,类型不兼容” 我不知道怎么了。。。 也许是struct中的struct有问题 非常感谢你的帮助! THX-亲切的问候 这是我的垃圾代码 结构声明: struct timeStamp { int year; int mon; int day; int hour; int min; }; struct weatherData {
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;
};
应返回结构的函数TimeOperation:
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;
};
在main()中,我想将“TimeOperation”返回的结构分配给另一个结构:
struct weatherData *pNew = NULL;
pNew->weatherStamp = timeManipulate(timeinfo);
函数应该返回一个指针
struct timeStamp *timeManipulate(struct tm *timeinfo)
/* ^ make the function return a struct tiemStamp pointer */
并且返回值应该是
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
分配空间
最后,不要强制转换
malloc()
的结果,它不是必需的。另一个解决方案是让weatherData
包含结构时间戳weatherStamp代码>,并停止使用malloc
。我看不出将部分数据卸载到malloc
有什么好处。