I am currently working on an assignment which requires me to create a struct of elements from input data (name, weight, symbol), and then assign each struct to a linked list before printing it out to the screen.
I am finally at a point where it is taking all of my input data, however, when it is printed out to the screen, the string values are all the same?
This is my code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define NO_OF_ELEMS 3
typedef struct ELEMENT {
const char* name;
double atomic_weight;
const char* atomic_symbol;
} elem;
typedef struct list {
elem data;
struct list *next;
} list;
list* create_list(elem e)
{
list* head = malloc(sizeof(e));
head->data = e;
head->next = NULL;
return head;
}
list* add_to_list(elem e, list* h)
{
list* head = create_list(e);
head->next = h;
return head;
}
void print_list(list *h, char * title)
{
printf("Name\t\tAtomic Weight\t\tAtomic Symbol\n");
while (h != NULL)
{
printf("%s\t\t%lf\t\t%s\n", h->data.name, h->data.atomic_weight, h->data.atomic_symbol);
h = h->next;
}
}
elem* create_element(const char *name, double weight, const char *symbol)
{
elem* e = malloc(sizeof(elem));
e->name = name;
e->atomic_weight = weight;
e->atomic_symbol = symbol;
return e;
}
int main()
{
list* list_of_elements;
int counter = 0;
while( counter < NO_OF_ELEMS)
{
char name[16], symbol[3];
double weight;
printf("Please Enter Atomic Element's Name: ");
scanf("%s", name);
printf("Please Enter Atomic Element's Weight (Floating Point number): ");
scanf("%lf", &weight);
printf("Please Enter Atomic Element's Chemical Symbol: ");
scanf("%s", symbol);
elem* e = create_element(name, weight, symbol);
if(counter < 1)
{
list_of_elements = create_list(*e);
}
else
{
list_of_elements = add_to_list(*e, list_of_elements);
}
counter++;
printf("%d / %d\n", counter, NO_OF_ELEMS);
}
print_list(list_of_elements, "Periodic Table Elements");
return 0;
}
The code compiles fine, with no errors or warnings. However, this is the output I am getting:
me@my-mbp assessments % ./periodic
Please Enter Atomic Element's Name: Helium
Please Enter Atomic Element's Weight (Floating Point number): 0.32244
Please Enter Atomic Element's Chemical Symbol: He
1 / 3
Please Enter Atomic Element's Name: Hydrogen
Please Enter Atomic Element's Weight (Floating Point number): 0.4254
Please Enter Atomic Element's Chemical Symbol: H
2 / 3
Please Enter Atomic Element's Name: Oxygen
Please Enter Atomic Element's Weight (Floating Point number): 0.42534
Please Enter Atomic Element's Chemical Symbol: O2
3 / 3
Periodic Table Elements
Name Atomic Weight Atomic Symbol
Oxygen 0.425340 O2
Oxygen 0.425400 O2
Oxygen 0.322440 O2
Can anyone suggest why this is happening?