0

What can be the main issues in this code.

This is the case when I try to print first two elements: https://drive.google.com/file/d/1Ve9HH4tzBmWGZsW5lHjNrTXtHNh1w33o/view?usp=sharing

This is the case while inputting the third element. https://drive.google.com/file/d/1NA-Oyh44aA4C_CtGXLbbM_m5DgEUnOQn/view?usp=sharing

#include<stdio.h>
#include<stdlib.h>
#include <string.h>
#include<ctype.h>

typedef struct atom{ char name[20];
                     char symbol[2];
                     double weight;
                     struct atom *next;} atom;

int is_empty(const atom *a)
{ return (a == NULL);
}

atom *create_list(char name[], char symbol[], double weight)
{ atom *head= malloc(sizeof(atom));
  memcpy(name, head->name, strlen(head->name));
  memcpy(symbol, head->symbol, strlen(head->symbol));
  head->weight=weight;
  head->next=NULL;
  return head;
}

atom *add_to_front(char name[], char symbol[], double weight, atom *h)
{ atom *head = create_list(name, symbol, weight);
  head->next=h;
  return head;
}

atom *array_to_list ()
{ char name[20]="Hydrogen";
  char symbol[2]="H";
  double weight=1.008;
  int size=10;
  atom *head=create_list(name, symbol, weight);
  int i;
  for (i=1; i<size; i++)
  {  printf("Enter the element %d: ", i+1);
     gets(name);
     printf("Enter the symbol %d: ", i+1);
     gets(symbol);
     printf("Enter the weight %d: ", i+1);
     scanf("%lf", &weight);
     head=add_to_front(name, symbol, weight, head);
  }
  return head;
}

void print_list(atom *a, char *title)
{ printf("%s\n", title);
  while (a!= NULL)
  { printf("Atom: %s\n\n", a->name);
    printf("Symbol: %s\n\n", a->symbol);
    printf("Weight: %lf\n\n", a->weight);
    a=a->next;
  }
}

int main()
{ atom list_of_int;
  atom *head=NULL;
  head=array_to_list();
  print_list(head, "Atoms");
  printf("\n\n");
  return 0;
}
Deb Jyoti
  • 29
  • 3
  • `scanf("%lf", &weight);` leaves a newline in stdin and the next call to `gets` reads that. – 001 Jan 20 '22 at 17:51
  • [Please do not upload images of code/errors when asking a question.](//meta.stackoverflow.com/q/285551) – 001 Jan 20 '22 at 17:53
  • Note that `symbol` should be `char[3]` to allow room for the terminating null byte, and that in your `memcpy` calls you have source and destination reversed. – SGeorgiades Jan 20 '22 at 18:23

0 Answers0