2

I'm trying to increase the day of a date struct in C. I keep getting a return where the memory seems to be adding [not the actual int day in the struct].

For example, if I INPUT:

2018 10 2

I should get

OUTPUT:

10/03/2018

INSTEAD, I GET:

32594/10/-352487872

I believe I'm not using pointers correctly in the method: advanceDay(struct date d)

#include <stdio.h>

struct date {
        int year;
        int month;
        int day;
    };

/* function prototypes */
void printDate(struct date);
void readDate(struct date *);
struct date advanceDay(struct date); 

int main(void) {
    struct date today, tomorrow;
    readDate(&today);
    printDate(today);
    tomorrow = advanceDay(today);
    printDate(tomorrow);
    return 0;
}

/* add your function definitions here */
void printDate(struct date d) {
    printf("%02d/%02d/%04d\n", d.month, d.day, d.year);
}

void readDate(struct date *d){
    scanf("%d %d %d", &(d->year), &(d->month), &(d->day));
}

struct date advanceDay(struct date d) {
    d.day = d.day+1;
}

I've tried to change d.day = d.day+1; to d.day = (*d.day)+1; But I get an error. I've tried the -> and also moving around the *

2 Answers 2

2

Note that advanceDay doesn't explicitly return anything, resulting in undefined behavior (and probably reading uninitialized memory - the compiler should have warned you about it).

Instead, you could pass a struct date* to the function, and update it in place:

void advanceDay(struct date * d) {
    d->day = d->day + 1;
}

Note that your main also needs to change accordingly:

int main(void) {
    struct date today;
    readDate(&today);
    printDate(today);
    advanceDay(&today); /* no retrun value here */
    printDate(today); /* today was updated in-place */
    return 0;
}
Sign up to request clarification or add additional context in comments.

2 Comments

I think you forgot to change the return type to void in your fixed code.
@kopecs indeed, copy-and-bug :-( Thanks for noticing, edited and fixed.
1

You declare advanceDay to return a value, but you don't return anything. You invoke undefined behavior by failing to return a value from this function and then subsequently attempting to use the return value.

Create a copy of the passed in struct date, perform the operation on the copy, and return it.

struct date advanceDay(struct date d) {
    struct date nextDay;
    nextDay.day = nextDay.day+1;
    return nextDay;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.