I want to reach linked list like an array. I write a code like that but i get unexpected result. Main problem is, when i check sizeof(myrecord) value, i get 27 bytes, but actually difference between the records is 32 bytes. Do you know where is the error?
#include <stdio.h>
#include <conio.h>
#include <string.h>
#include <stdlib.h>
struct myrecord {
int number;
char name[15];
myrecord *next;
myrecord *previous;
} *now, *first, *last; // sizeof(myrecord) function returns 27 bytes
void add(int no, char nm[15]) {
now = (myrecord *) malloc(sizeof(myrecord));
now->number = no;
strcpy(now->name , nm);
now->next = NULL;
if (first == NULL) { //if first record
now->previous = NULL;
first = now;
} else { //if not first record
last->next = now;
now->previous = last;
}
last = now;
}
int main() {
first = NULL;
add(25,"abc");
add(20,"xyz");
add(30,"def");
//No problem in here
printf("%d %s\n" , first->number , first->name); // Normally 25 and abc
// Problem starts here. I expected 20 and xyz but first+1 going to a wrong adress
//there is 32 bytes between the records but first+1 going to 27 bytes further
printf("%d %s\n" , (first+1)->number , (first+1)->name); // Wrong results
// Still not true values. I expected 30 and def but first+2 going to a wrong adress
printf("%d %s\n" , (first+2)->number , (first+2)->name); // Wrong results
getch();
return 0;
}