macinbacon
macinbacon

Reputation: 1

Pointer to a typedef in a function?

I'm completely new to C and coding in general, please be patient with me. I want to learn how to use pointers with a typedef structure inside of a function. As far as I know my code isn't wrong and there's no warnings/errors, anything could help, thank you

typedef struct
{
     double year, month, day;
} Date;

void changedate(Date red)
{
     Date* blue = &red;
     blue->year = 2022;
     blue->month = 5;
     blue->day = 7;
}

int main(void)
{
     Date pee = {2002, 5, 17};
     printf("This is the date: %.0lf/%.0lf/%.0lf\n", pee.year, pee.month, pee.day);
     changedate(pee);
     printf("This is the date: %.0lf/%.0lf/%.0lf  ", pee.year, pee.month, pee.day);

     keypress();
     return 0;
}

So yeah, I'm trying to get it to store the new date values and print it out, but it doesn't seem to work. Anything could help

Upvotes: 0

Views: 84

Answers (1)

Darth-CodeX
Darth-CodeX

Reputation: 2437

Some Points:
  • unsigned int will do the job, there's no need for double data type
  • You need to pass the address to the function, or return the changed Date, and then assign it to pee
  • keypress() is not a standard function
  • pee isn't a good word for a variable
Final Code:
#include <stdio.h>

typedef struct {
    unsigned int year, month, day;
} Date;

void changedate(Date *red) {
    red->year = 2022;
    red->month = 5;
    red->day = 7;
}

int main(void) {
    Date red = {2002, 5, 17};
    printf("This is the date: %u/%u/%u\n", red.year, red.month, red.day);
    changedate(&red);
    printf("This is the date: %u/%u/%u\n", red.year, red.month, red.day);
    return 0;
}
Another Approach
#include <stdio.h>

typedef struct {
    unsigned int year, month, day;
} Date;

Date changedate(Date red) {
    red.year = 2022;
    red.month = 5;
    red.day = 7;
    return red;
}

int main(void) {
    Date red = {2002, 5, 17};
    printf("This is the date: %u/%u/%u\n", red.year, red.month, red.day);
    red = changedate(red);
    printf("This is the date: %u/%u/%u\n", red.year, red.month, red.day);
    return 0;
}

Upvotes: 2

Related Questions