Array of Structures in C missing data? -
i designing program in c. part of program involves reading table of data relating periodic table , elements file, , putting in structure.
so far, it's working rather well. however, reason, when try display array, couple of elements don't show up, instead blanks. show earlier in code, though.
main.c
main() { struct periodic *tableptr; tableptr = createtable(); printf("%d\t",(tableptr+90)//prints "pa" here expected int i; for(i=0;i<num_elements;i++){ printf("%d\t%s\n",i,(tableptr+90)->sym);//prints i, blank. } }
periodic.c (creates table)
#include "periodic.h" #include <stdio.h> struct periodic *createtable(){ char format[] ="%d\t%s[3]\t \ %s[20]\t%f\t \ %s[100]\t%f\t \ %d\t%f\t%d\t \ %d\t%d\t%s[20]\t \ %s[7]\t%s[17]\t \ %d\t%d\t%f\t \ %s[40]\n)"; struct periodic period_table[num_elements]; struct periodic *tableptr = period_table; file *fp; fp = fopen("periodictable.csv","r"); char buff[200]; struct periodic *initptr = tableptr; while(fgets(buff,sizeof(buff),fp)){ sscanf(buff,format,&(tableptr->num),&(tableptr->sym),&(tableptr->name),&(tableptr->weight),&(tableptr->config),&(tableptr->neg),&(tableptr->ion_rad),&(tableptr->vdw_rad),&(tableptr->ie_1),&(tableptr->ea),&(tableptr->oxi_st),&(tableptr->stn_st),&(tableptr->melt),&(tableptr->boil),&(tableptr->dens),&(tableptr->type)); tableptr++; } fclose(fp); return initptr; }
i can give more information needed.
you have:
struct periodic *tableptr = period_table;
here, tableptr
points array defined locally in function. , return tableptr
function. when function returns, array destroyed. hence, calling function has dangling pointer.
referencing dangling pointer leads undefined behavior.
you need allocate memory heap, return pointer dynamically allocated memory, , deallocate memory in calling function.
struct periodic *tableptr = malloc(sizeof(*tableptr)*num_elements);
and in main
, call
free(tableptr);
before function ends.
also, add explicit return type main
.
int main() { ... }
Comments
Post a Comment