Home > Mobile >  Pointer to a typedef in a function?
Pointer to a typedef in a function?

Time:05-07

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

CodePudding user response:

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

CodePudding user response:

#include <iostream>
using namespace std;

int plusFunc(int x, int y) {
  return x   y;
}

double plusFunc(double x, double y) {
  return x   y;
}

int main() {
  int myNum1 = plusFunc(8, 5);
  double myNum2 = plusFunc(4.3, 6.26);
  cout << "Int: " << myNum1 << "\n";
  cout << "Double: " << myNum2;
  return 0;
}
  •  Tags:  
  • c
  • Related