我的结构看起来像这样:
struct table2
{
int k;
float value;
int row;
int col;
int nextK_row;
int nextK_col;
};
int allocate(int k, int n, struct table2 *table2_entry,struct table3 *table3_entry)
{
//allocate memory to table2
table2_entry=(struct table2*)malloc((sizeof(struct table2))*k);
if(table2_entry==0)
{
printf("Out of memory\n");
return 1;
}
table3_entry=(struct table3*)malloc((sizeof(struct table3))*n);
if(table3_entry==0)
{
printf("Out of memory\n");
return 1;
}
return 0;
}
如果我在main函数中执行此操作:
for(i=1;i<=k;i++)
{
fscanf(source,"%d %f %d %d %d %d", &(table2_entry[i]).k,&(table2_entry[i]).value,&(table2_entry[i]).row,&(table2_entry[i]).col,&(table2_entry[i]).nextK_row,&(table2_entry[i]).nextK_col);
printf("%f\n",(table2_entry[i]).value);
}
它会起作用吗?还是我只是在监督什么?请帮助我。 :(
答案 0 :(得分:0)
为了使allocate
的调用者能够使用其中分配的内存,您必须将该函数更改为:
int allocate(int k, int n,
struct table2 **table2_entry,
struct table3 **table3_entry)
{
//allocate memory to table2
*table2_entry=(struct table2*)malloc((sizeof(struct table2))*k);
if(table2_entry==0)
{
printf("Out of memory\n");
return 1;
}
*table3_entry=(struct table3*)malloc((sizeof(struct table3))*n);
if(table3_entry==0)
{
printf("Out of memory\n");
return 1;
}
return 0;
}
然后,在另一个函数中,可以将其称为:
struct table2 *table2_entry = NULL;
struct table3 *table3_entry = NULL;
allocate(10, 3, &table2_entry, &tabl3_entry);
使用您拥有的版本,allocate
中分配的内存是泄漏。客户端代码无法获取它,因为指针是按值传递的。