'How to make struct point to previous array value
My schedule->start.hour points to the currect element of array. How to make it point to the previous element of array?
struct Time {
int hour;
} start, end;
struct Class {
struct Time start, end;
} schedule[100];
I need to use this inside a function which sets start of current to be equal to end of previous.
void add_class(struct Class shedule[]){
schedule->start.hour=schedule*(--).end.hour;
};
Solution 1:[1]
It seems you need something like the following
void add_class( struct Class shedule[], size_t n )
{
for ( size_t i = 1; i < n; i++ )
{
shedule[i].start.hour = shedule[i-1].end.hour;
}
//...
}
and the function is called like
add_class( shedule, sizeof( shedule ) / sizeof( *shedule ) );
or like
add_class( shedule, 100 );
Solution 2:[2]
Its not really clear what you are after and the code you show is wrong. There are no pointers there at all.
If you want to access different instances of Class in the schedule array you need
schedule[0].start.hour;
schedule[1].start.hour;
....
to loop over them all
for(int i = 0; i < 100; i++){
printf("start=%d, end = %d\n",schedule[i].start.hour, scehdule[i].end.hour);
}
if you have a pointer to a Class instance
void add_class(struct Class shedule[]){
...
};
You can access the prior entry in the array like this
void add_class(struct Class schedule[]){
struct Class *prior = schedule - 1;
schedule->start.hour=prior->end.hour;
};
But , and this is a huge but, this will be very bad if this is the first element in the array.
I would still do it by passing indexes tho.
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 | Vlad from Moscow |
| Solution 2 |
