I'm trying to iterate over an array of structs by pointer arithmetic. However it gives me results I can't understand.
#include <stdio.h>
#include <stdlib.h>
typedef struct
{
int hours;
int minutes;
int seconds;
} Time;
void time_print(Time t)
{
printf("Time is: %d:%d:%d\n", t.hours, t.minutes, t.seconds);
}
int main(void)
{
Time *testTimePointers[2];
testTimePointers[0] = malloc(sizeof(Time));
testTimePointers[0]->hours = 11;
testTimePointers[0]->minutes = 10;
testTimePointers[0]->seconds = 9;
testTimePointers[1] = malloc(sizeof(Time));
testTimePointers[1]->hours = 7;
testTimePointers[1]->minutes = 6;
testTimePointers[1]->seconds = 5;
time_print(*(testTimePointers[0]));
time_print(*(testTimePointers[1]));
printf("=============\n");
Time *ttp_cur = NULL;
ttp_cur = testTimePointers[0];
time_print(*(ttp_cur));
ttp_cur++;
time_print(*(ttp_cur));
free(testTimePointers[0]);
free(testTimePointers[1]);
return 0;
}
Results in
Time is: 11:10:9
Time is: 7:6:5
=============
Time is: 11:10:9
Time is: 0:0:0
In the second block, the second line should be Time is: 7:6:5 instead of Time is: 0:0:0.
ttp_cur++;pointer makes step equal to sizeof(Time) and points to nowhere.