Adding values ​​to a linked list to a variable

I am creating a C program to add values ​​to nodes in a Linked List by going through using a while loop.

I encoded 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 get the following output:

    33367

Instead of getting 600 as a day off

+4
source share
1 answer
  int sum;

Here you create a stack variable; the C standard says nothing about its meaning, and in practice it will contain any random bytes in the memory location where it is now stored. For more information about this, see here. What happens to a declared, uninitialized variable in C? Does it matter?

:

  int sum = 0;

, entry main ( , ).

+4

Source: https://habr.com/ru/post/1615963/


All Articles