I've created a periodic table program in C, with an dynamic field, or at least I tried.
I will extend the program later, with the other 116 elements, but for now, it will be like this.
Compiler says nothing, but I get a runtime error: 'memory access violation'
What did I overlooked/miss?
The Output should only show the saved elements (Aluminium/Radium).
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
typedef struct
{
char Name[20];
char Symbol[3];
char Atomicnumber[5];
char* entrys;
} Element;
int main(void)
{
//Define the two entrys/elements
Element Aluminium;
strcpy(Aluminium.Name, "Aluminium");
strcpy(Aluminium.Symbol, "Al");
strcpy(Aluminium.Atomicnumber, "13");
Element Radium;
strcpy(Radium.Name, "Radium");
strcpy(Radium.Symbol, "Ra");
strcpy(Radium.Atomicnumber, "88");
int size=0;
//Define field
printf ("size of field:");
scanf( "%d" , &size);
//Gives the saved Elements an Adress in Array/Field
Element Periodictable [size];
strcpy(Periodictable[13].Name, "Aluminium");
strcpy(Periodictable[13].Symbol, "Al");
strcpy(Periodictable[13].Atomicnumber, "13");
strcpy(Periodictable[13].entrys, "1");
strcpy(Periodictable[88].Name, "Radium");
strcpy(Periodictable[88].Symbol, "Ra");
strcpy(Periodictable[88].Atomicnumber, "88");
strcpy(Periodictable[88].entrys, "1");
void output(Element* Periodictable, int*entry);
printf("Recorded elements:\n");
printf("\n");
for (int i=1; i<= size; i++)
{
if (Periodictable[i].entrys)
{
printf("Name: %s \n",Periodictable[i].Name);
printf("Symbol: %s \n",Periodictable[i].Symbol);
printf("Atomic number: %s \n",Periodictable[i].Atomicnumber);
printf("\n");
}
else i++;
}
return (0);
}
output should be like this:
Recorded elements:
Name: Aluminium
Symbol: Al
Atomic number: 13
Name: Radium
Symbol: Ra
Atomic number: 88
The defined field should still be created, but the empty fields/adresses should not be shown in the console
entrysis a character pointer without any memory allocated to it. Therefore this linestrcpy(Periodictable[13].entrys, "1");will fail - Ed Heal