本文介绍了在分配结构C.动态数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在分配C. Valgrind的结构的动态数组发现了这个错误:大小8.未初始化值使用错误弹出试图访问该struct成员

什么是避免方式?

 无效find_rate()
{
  INT NUM_LINES = 0;
  FILE *的;
  结构记录** data_array中;
  双*距离;
  结构记录user_record;  在= OPEN_FILE();  NUM_LINES = count_lines(上);  allocate_struct_array(data_array中,NUM_LINES);  data_array中[0] - GT; COMMUNITY_NAME [0] =H; //错误是在这里
  的printf(%C \\ N,将data_array [0] - >团体名称[0]);  fclose函数(在);
}FILE * OPEN_FILE()
{
  .....一些code打开文件
  返回F;
}INT count_lines(FILE * F)
{
  在文件....计数行
  回线;
}

下面是我的方式分配数组:

 无效allocate_struct_array(结构记录**阵列,INT长度)
{
  INT I;  阵列=的malloc(长*的sizeof(结构记录*));  如果(!数组)
    {
      fprintf中(标准错误,无法分配的结构*记录\\ n阵);
      出口(1);
    }  对于(i = 0; I<长度;我+ +)
    {
      数组[我] =的malloc(sizeof的(结构记录));      如果(!数组[I])
    {
      fprintf中(标准错误,无法分配数组内容[%d] \\ n,I);
      出口(1);
    }
    }
}


解决方案

既然你传递数组的地址给函数 allocate_struct_array

您需要:

  *数组=的malloc(长*的sizeof(结构记录*));

和调用函数中你需要声明 data_array中为:

 结构记录* data_array中;

,并通过其地址为:

  allocate_struct_array(安培; data_array中,NUM_LINES);

Allocating dynamic array of struct on C. Valgrind found this error: Use of uninitialised value of size 8. The error pops up while trying to access the struct member.

What is the way to avoid that?

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;
}

Here is the way I allocate the array:

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);
    }
    }
}
解决方案

Since you are passing the address of array to the function allocate_struct_array

You need:

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

And in the calling function you need to declare data_array as:

struct record * data_array;

and pass its address as:

allocate_struct_array(&data_array, num_lines);

这篇关于在分配结构C.动态数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-19 12:37