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

Recommended Answers

All 2 Replies

1. You must be compiling that program as c++, not C because C requires the keyword struct before each use of the structure name, such as struct mystrut . Change the file extension of the program file to *.c

2. >>(first+1)->number
You can't access members like that because its a linked list, not an array. The correct way is first->next->number Its a lot simpler to use a loop

struct mystruct* node = first;
while( node )
{
   printf("%s\n",node->name);
   node = node->next;
}

sizeof() is not an issue if you use ->next as recommended above, however, here are some details:
1) sizeof() is returning the number of bytes you used (4 + 15 + 4 + 4) = 27,
but the compiler rounds up to a multiple of 3, 8, 16, or 32, depending on options.
You can expect the compiler (and malloc()) to reserve an arbitrary number of bytes (zero or more) than you requested.

2) You cannot assume that multiple calls to malloc() return equally-spaced pointers. You must treat each allocated block as if it was randomly located relative to the other blocks.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.