0

In this program I created a array(node[3]) of structure(struct eg) and made them as linked lists while trying to print the elements of the list I am getting only 1 output that is 3

#include<stdio.h>
#include<conio.h>
#include<stdlib.h>

struct eg
{
    struct eg *next;
    int age;
}node[3];

main()
{
    struct eg *head,*temp;
    int i;

    head=temp=node;
    for(i=1;i<3;i++)
    {
       temp->age=i;
       temp->next=temp+i;
    }
    temp->next=0;
    temp->age=3;
    while(head!=0)
    {
       printf("%d",head->age);
       head=head->next;
    } 
}
3
  • Please have a look at How to create a Minimal, Complete, and Verifiable example, and review your post. Commented Sep 8, 2016 at 16:56
  • 4
    @HopefulLlama I think the code in the question is pretty much MCVE. Commented Sep 8, 2016 at 16:58
  • Okay, my bad. Must just be me then. Commented Sep 8, 2016 at 17:01

1 Answer 1

2
temp->next=temp++;

You're reading and modifying temp in a single expression with no sequence point. This invokes undefined behavior.

You need to separate the increment from the assignment:

temp->next=temp+1;
temp++;
Sign up to request clarification or add additional context in comments.

1 Comment

You could even move the temp++ into the increment part of the for to make it clear that it is incremented for each loop (i.e. for(i=1;i<3;i++,temp++))

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.