'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
Solution 1:[1]
Some Points:
unsigned intwill do the job, there's no need fordoubledata type- You need to pass the address to the function, or return the changed
Date, and then assign it topee keypress()is not a standard functionpeeisn'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;
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
