我应该返回函数中的指针,以便我可以使用它们吗?例如,我应该返回table2_entry吗?

时间:2014-03-29 06:05:37

标签: c pointers struct

我的结构看起来像这样:

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);
}
它会起作用吗?还是我只是在监督什么?请帮助我。 :(

1 个答案:

答案 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中分配的内存是泄漏。客户端代码无法获取它,因为指针是按值传递的。

相关问题