[英]Array of Structures in C missing data?
I am designing a program in C. Part of the program involves reading a table of data relating to the periodic table and its elements from a file, and putting it in a structure. 我正在用C设计程序。程序的一部分包括从文件中读取与周期表及其元素有关的数据表,并将其放入结构中。
So far, it's working rather well. 到目前为止,它运行良好。 However, for some reason, when I try to display the array, a couple of elements don't show up, but instead blanks.
但是,由于某种原因,当我尝试显示数组时,几个元素没有显示,而是空白。 It does show up earlier in the code, though.
不过,它确实出现在代码的前面。
main.c main.c
main()
{
struct periodic *tablePtr;
tablePtr = createTable();
printf("%d\t",(tablePtr+90)//Prints "Pa" here as expected
int i;
for(i=0;i<num_elements;i++){
printf("%d\t%s\n",i,(tablePtr+90)->sym);//Prints i, but then just blank.
}
}
periodic.c (creates the table) periodic.c(创建表)
#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 as needed. 我可以根据需要提供更多信息。
You have: 你有:
struct periodic *tablePtr = period_table;
Here, tablePtr
points to an array that is defined locally in the function. 在这里,
tablePtr
指向在函数中本地定义的数组。 And then you return tablePtr
from the function. 然后从该函数返回
tablePtr
。 When the function returns, the array is destroyed. 函数返回时,数组将被销毁。 Hence, the calling function has a dangling pointer.
因此,调用函数具有一个悬空指针。
Referencing a dangling pointer leads to undefined behavior. 引用悬空指针会导致未定义的行为。
You need to allocate memory from the heap, return a pointer to the dynamically allocated memory, and deallocate the memory in the calling function. 您需要从堆中分配内存,返回指向动态分配的内存的指针,然后在调用函数中取消分配内存。
struct periodic *tablePtr = malloc(sizeof(*tablePtr)*num_elements);
and in main
, call main
是打电话
free(tablePtr);
before the function ends. 在函数结束之前。
Also, add an explicit return type to main
. 另外,向
main
添加显式返回类型。
int main()
{
...
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.