I have a struct in C, and I create an array of this struct
typedef struct {
int aNum;
char name[20];
char sym[10];
char class[30];
float weight;
int shell[SHELLS];
} element_t;
element_t elements[MAX_ELEMENTS];
I am asking the user for an input (1 Hydrogen H other_nonmetals 1.008 1 0 0 0 0 0 0
), and I separate it into an array based on the spaces.
I get each user input by calling a function,
for(int i=0;i<N;i++)
scan_element(i);
function:
void scan_element(int i) {
char *array[12];
char str[100];
int j=0;
if (fgets(str, 100, stdin)) {
array[j] = strtok(str," ");
while(array[j]!=NULL)
{
array[++j] = strtok(NULL," ");
}
}
elements[i].aNum = (int) strtol(array[0], NULL, 10);
if(i>0)
for(int k=5;k<SHELLS+5;k++)
printf("%d ",elements[i-1].shell[k]);
printf("\n");
strcpy(elements[i].name, array[1]);
strcpy(elements[i].sym, array[2]);
strcpy(elements[i].class, array[3]);
elements[i].weight = (strtod(array[4],NULL));
for(int k=5;k<SHELLS+5;k++)
elements[i].shell[k] = (int) strtol(array[k], NULL, 10);
}
If I just input 1 element, the shell int array is fine, but when I input another element, it messes up the previous element's shell array. It should look like 1 0 0 0 0 0 0
, and it does for the current element, but when I input another element, the shell array looks like 1 0 82 1684104524 0 0 0
. I figured it happens after I call strcpy
, as before it prints out fine, but right after the first time I call strcpy
, it adds random numbers to the array.
How can I fix it so that so I can enter multiple elements without it messing up the previous element's shell array? It only messes up the shell array, nothing else from the previous struct.