C语言结构体动态数组的分配



在c语言上分配struct的动态数组,Valgrind发现这个错误:使用大小为8的未初始化值。当试图访问结构成员时弹出错误。

如何避免这种情况?

void find_rate()
{
  int num_lines = 0;
  FILE * in;
  struct record ** data_array;
  double * distance;
  struct record user_record;
  in = open_file();
  num_lines = count_lines(in);
  allocate_struct_array(data_array, num_lines);
  data_array[0]->community_name[0] = 'h';       // the error is here
  printf("%cn", data_array[0]->community_name[0]);
  fclose(in);
}
FILE * open_file()
{
  ..... some code to open file
  return f;
}
int count_lines(FILE * f)
{
  .... counting lines in file
  return lines;
}
下面是我分配数组的方式:
void allocate_struct_array(struct record ** array, int length)
{
  int i;
  array = malloc(length * sizeof(struct record *));
  if (!array)
    {
      fprintf(stderr, "Could not allocate the array of struct record *n");
      exit(1);
    }
  for (i = 0; i < length; i++)
    {
      array[i] = malloc( sizeof(struct record) );
      if (!array[i])
    {
      fprintf(stderr, "Could not allocate array[%d]n", i);
      exit(1);
    }
    }
}

由于您将数组的地址传递给函数allocate_struct_array

你需要

:

*array = malloc(length * sizeof(struct record *));

在调用函数中,您需要将data_array声明为:

struct record * data_array;

并将其地址传递为:

allocate_struct_array(&data_array, num_lines);

最新更新