Katie Melosto
Katie Melosto

Reputation: 1177

adding a int from a struct pointer

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 *

Upvotes: 2

Views: 316

Answers (2)

Mureinik
Mureinik

Reputation: 311143

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

Upvotes: 2

dbush
dbush

Reputation: 223699

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

Upvotes: 1

Related Questions