在C上分配struct的动态数组

时间:2011-12-10 07:18:34

标签: c

在C.上分配动态数组struct Valgrind发现此错误:使用大小为8的未初始化值。尝试访问struct成员时会弹出错误。

避免这种情况的方法是什么?

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("%c\n", 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);
    }
    }
}

1 个答案:

答案 0 :(得分:3)

因为您将数组的地址传递给函数allocate_struct_array

你需要:

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

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

struct record * data_array;

并将其地址传递为:

allocate_struct_array(&data_array, num_lines);