KayoZ
KayoZ

Reputation: 13

C - struct as a return value does not fit

when I compile my programm I get an error telling me: "incompatible types when assigning to type 'struct timeStamp *' from type 'struct timeStamp'"

I don't have any clue what's wrong... Maybe it's a problem with the struct in struct?

Very thankful for your help! THX - kind regards!

Here's my crap code...

struct declaration:

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;
};

the function timeManipulate that should return a struct:

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() I want to assign the struct returned by "timeManipulate" to the other structure:

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

Upvotes: 1

Views: 61

Answers (1)

Iharob Al Asimi
Iharob Al Asimi

Reputation: 53026

Your function should return a pointer

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

and the return value should be

return tS;

Also, your

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

will still dereference the NULL pointer, it should be something like

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

and this will not work of course

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

you must allocate space for pNew too.

Finally don't cast the result of malloc() it's not needed.

Upvotes: 1

Related Questions