C 中的动态数组

Dynamic arrays in C

我正在尝试动态创建一个具有随机值的矩形数组。但是,当尝试访问 space I malloc 时出现段错误。

我的代码:

typedef struct Point
{
    double x;
    double y;
} PointT;

typedef struct Rect
{
    PointT location;
    char color;
    double w; //width
    double h; //height
} RectT;
main()
{
    RectT *recs;
    randRect(&recs);
}
void randRect(RectT **rects)
{
    int i;
    rects =malloc(numRec*sizeof(RectT*));
    for(i = 0; i < numRec-1; i++)
    {
          rects[i]->w=rand()%20;
          rects[i]->h=rand()%20;
          rects[i]->location.x=rand()%20;
          rects[i]->location.y=rand()%20;
    }
}

numRec 定义为 50

您为 RectT 指针 的数组分配 space,但您从未为 RectT 分配 space他们指向 .

函数中的rects是指向指针的指针。所以你需要在使用它之前分配 RectT 项目的数组。应该是这样的:

void randRect(RectT **rects)
{
    int i;
    *rects =malloc(numRec*sizeof(RectT));
    for(i = 0; i < numRec; i++)
    {
      (*rects)[i].w=rand()%20;
      (*rects)[i].h=rand()%20;
      (*rects)[i].location.x=rand()%20;
      (*rects)[i].location.y=rand()%20;
    }
}

或者更好的方法:

Rect* randRect()
{
    int i;
    Rect* rects =malloc(numRec*sizeof(RectT));
    for(i = 0; i < numRec; i++)
    {
      rects[i].w=rand()%20;
      rects[i].h=rand()%20;
      rects[i].location.x=rand()%20;
      rects[i].location.y=rand()%20;
    }
    return rects;
}

您需要为矩形分配 space,而不是指向矩形的指针:

void randRect(RectT **rects) }
  *rects = malloc(numRec * sizeof(RectT));

  for (size_t i = 0; i != numRec; ++i) {
    (*rects)[i]->w = 0; // etc
  }
}