开发者社区> 问答> 正文

在C中将指针传递给结构数组

您好,我是C语言的新手,在头文件和将指针结构传递给函数时遇到了一些麻烦,希望有人可以帮助我,我正在为一门课程做作业,教授在我要求澄清时无济于事,我确实不知道要去哪里。任务是构建一个程序,该程序将在二维空间中维护标记点的数组并实现在头文件中定义的功能原型。我在尝试实现addPoints()时遇到麻烦,我想我只需要一些有关如何在指向数组的函数时将指针传递给它们的帮助。我不只是在寻找任务的解决方案,我真的只是无法抓住这个话题,并且希望获得任何帮助。

ShapeT *initialize(int capacity){
    PointT *arrPoint = (PointT*)malloc(capacity * sizeof(PointT));
    ShapeT *shapeObj = (ShapeT*)malloc(sizeof(ShapeT));
    shapeObj->size = 0;
    shapeObj->capacity = capacity;
    shapeObj->points = arrPoint;
    if(arrPoint == NULL || shapeObj == NULL){
       return NULL;
    }
return shapeObj;
}

int addPoint(PointT point, ShapeT *shape){

}
从头文件

/*
* adds a point to the array referred to by `shape`. 
* This function returns 1 if it successfully adds a point, 
* or returns 0 if it can't add a point because the array is full.
*/
int addPoint(PointT point, ShapeT *shape);

展开
收起
kun坤 2019-11-29 11:27:58 343 0
1 条回答
写回答
取消 提交回答
  • 该addPoint功能可以实现如下:
    
    int addPoint(PointT point, ShapeT *shape)
    {
      if( !shape->capacity ) // capacity = 0 means not possible to add PointT
      {
          printf("The array is full. \n");
          return 0; 
      }
      else{ // copy the contents of the struct PointT to the array shape
          //Here 'shape->ponits' is a pointer that points to the array of struct PonitT
          shape->points[shape->size].x = point.x;
          shape->points[shape->size].y = point.y;
          shape->points[shape->size].num = point.num;
      }
      shape->size++; 
      shape->capacity--;
      return 1; 
    }
    在主要功能中:
    
    int main()
    {
      ShapeT * shape = initialize(2);
      PointT point, point2; // Adding two points for instance 
      point.x = 2;
      point.y = 3;
      point.num = 1;
      addPoint(point, shape);
    
      point2.x = 6;
      point2.y = -7;
      point2.num = 12;
      addPoint(point2, shape);
    
      // Checking the value of point2's y value
      printf("ponit2 x value = : %d\n", shape->points[1].y);
      printf("Capacity : %d\n", shape->capacity);
      return 0;
    }
    
    
    2019-11-29 11:28:09
    赞同 展开评论 打赏
问答分类:
问答标签:
问答地址:
问答排行榜
最热
最新

相关电子书

更多
低代码开发师(初级)实战教程 立即下载
冬季实战营第三期:MySQL数据库进阶实战 立即下载
阿里巴巴DevOps 最佳实践手册 立即下载