Home > Blockchain >  How to make struct point to previous array value
How to make struct point to previous array value

Time:03-14

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

CodePudding user response:

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

CodePudding user response:

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.

CodePudding user response:

Since schedule is a pointer, decrement it or use (schedule - 1).

BTW, instead of schedule->start.hour you can write schedule[0].start.hour, and then schedule[-1].start.hour will access the start hour of the previous element.

Please make sure that you have an element there.

  • Related