4

I am creating C program to add up the values in the nodes in Linked List by traversing using while loop.

I have coded the following:

#include <stdio.h>

int main (void)
 {
   struct entry
      {
      int            value;
      struct entry   *next;
      };

   struct entry   n1, n2, n3;
   struct entry   *list_pointer = &n1;
   int sum;
   n1.value = 100;
   n1.next  = &n2;

   n2.value = 200;
   n2.next  = &n3;

   n3.value = 300;
   n3.next  = (struct entry *) 0;    // Mark list end with null pointer

   while ( list_pointer != (struct entry *) 0 ) {
        sum += list_pointer->value;
        list_pointer = list_pointer->next;
     }

  printf ("%i\n", sum);


 return 0;
}

However I am getting the following output:

    33367

Instead of getting 600 as the output

alk
  • 69,737
  • 10
  • 105
  • 255
compcrk
  • 411
  • 4
  • 9
  • 18
  • 1
    You have never initialized sum, so its value is undefined. It contains whatever rubbish was on the stack where it's now stored. You should do `int sum = 0`. Also, please don't use nested struct declarations unless you have a really good reason to do so (in this case, you should pull `entry` out of `main`). – user4520 Nov 15 '15 at 15:13
  • Thanks , it works perfectly now :) – compcrk Nov 15 '15 at 15:16
  • @szczurcio: Why not make this comment an answer? – alk Nov 15 '15 at 15:16
  • 1
    @alk Done, thanks for the suggestion. – user4520 Nov 15 '15 at 15:20

1 Answers1

4
  int sum;

Here you're creating a stack variable; the C standard doesn't say anything about its value, and in practice it will contain whatever random bytes were at the memory location where it's now stored. For more information on this, see here: What happens to a declared, uninitialized variable in C? Does it have a value?

You should explicitly initialize it to zero:

  int sum = 0;

On another note, there's absolutely no reason for entry to be defined inside main (in general you should avoid nested struct declarations unless you have a good reason not to).

Community
  • 1
  • 1
user4520
  • 3,401
  • 1
  • 27
  • 50