作者:wr人在峡 | 来源:互联网 | 2023-10-12 18:38
你好,我是C语言的新手,在头文件和将指针结构传递给函数时遇到了一些麻烦,希望有人可以帮助我,我正在为课程分配作业,而教授在我要求澄清时无济于事而且我不知道还要去哪里。任务是构建一个程序,该程序将在二维空间中维护标记点的数组并实现在头文件中定义的功能原型。我在尝试实现addPoints()时遇到麻烦,我想我只需要一些有关如何在指向数组的函数时将指针传递给它们的帮助。我不只是在寻找任务的解决方案,我真的只是无法抓住这个话题,并且希望获得任何帮助。
包括“ geometry.h”
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);
enter image description here
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;
}