C 如何动态分配';typedef结构';元素?
我定义了这种类型:C 如何动态分配';typedef结构';元素?,c,dynamic,typedef,allocation,C,Dynamic,Typedef,Allocation,我定义了这种类型: typedef struct element { uint16_t value_raw; float value_scaled; char *tag; char *id; float scale; } element; 我需要为一个文件全局声明这些类型的数组,因为同一文件中的其他一些函数需要访问它。但在读取配置文件之前,我不知道数组的大小,所以我需要动态分配它。我试过这个: element *pv; int main() {
typedef struct element
{
uint16_t value_raw;
float value_scaled;
char *tag;
char *id;
float scale;
} element;
我需要为一个文件全局声明这些类型的数组,因为同一文件中的其他一些函数需要访问它。但在读取配置文件之前,我不知道数组的大小,所以我需要动态分配它。我试过这个:
element *pv;
int main()
{
int i;
int size = findoutthesize();
pv = malloc(sizeof(element) * size);
/* and then access the elements like this */
for (i = 0; i < size; i++)
pv[i].scale = (float) i;
}
元素*pv;
int main()
{
int i;
int size=findoutthesise();
pv=malloc(元件尺寸)*尺寸;
/*然后访问像这样的元素*/
对于(i=0;i
但事情并不像我想象的那样。。。。(所有.scale成员最终都是相同的值,即大小为1)
动态分配“element”类型数组以便访问数组中每个元素的成员的正确方法是什么?请确保第199行和第200行有问题:
e.tag = tag;
e.id = idbuf;
char-tag[80]
和char-idbuf[80]
是局部变量,因此e.tag
/e.id
指针仅在get\u元素
函数结束之前有效
在这里:
并且,在
get_元素
函数中,直接对e.tag
/e.id
进行操作,您的代码正确且比例
已正确初始化(例如,请参阅)。你如何检查比例的值?
?它实际上是一个更大文件的一部分,我不想在这里发布,以防吓跑任何人,但我可能掩盖了真正的问题。。。。你可以看到我在第293行尝试做同样的事情
for (i = 0; i < modbus_read_count; i++)
{
pv[i] = get_element(fp, line);
printf("tag=%s, id=%s, scale=%.1f\n", pv[i].tag, pv[i].id, pv[i].scale);
}
typedef struct element
{
uint16_t value_raw;
float value_scaled;
char tag[80];
char id[80];
float scale;
} element;