大佬教程收集整理的这篇文章主要介绍了将元素添加到 malloc 数组的中间,大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
我创建了一个函数,允许从我的 malloc(ed) 数组(结构三角形坐标列表)中删除一个元素。这很好用。 但是当我尝试创建一个添加元素(在位置 i 之后)时,它就行不通了...@H_674_3@
例如,如果我有一个 [0] [1] [2] [3] [4] [5] 的数组,并且想在 [3] 之后添加一个新值。@H_674_3@
这是我的代码:(这是我的while循环中的一个片段)@H_674_3@
@R_851_10586@ltri++;
addtriangle(triList,@R_851_10586@ltri,i);
i++;
secondtriangle(p,&t1,&t2,&t3,v,i);
i++;
我的代码 deletetriangle(....):@H_674_3@
for (int c = i; c < @R_851_10586@ltri; c++)
{
triList[c] = triList[c+1];
}
tmp = (triangle *) realloc(triList,(@R_851_10586@ltri-1)*sizeof(trianglE));
triList = tmp;
我的代码 addtriangle(....):这似乎不起作用..!@H_674_3@
tmp = (triangle *) realloc(triList,(@R_851_10586@ltri+1)*sizeof(trianglE));
for (int c = @R_851_10586@ltri; c > i; c--)
{
triList[c-1] = triList[c];
}
triList = tmp;
然后我继续为刚刚添加到此代码中的第二个三角形赋值:@H_674_3@
int p1,p2,p3;
p1 = whereisthepoint(p,*t1,v);
p2 = whereisthepoint(p,*t2,v);
p3 = whereisthepoint(p,*t3,v);
triptr=&(triList[i]);
triptr->corner=(point *) malloc(3*sizeof(point));
pt1ptr=&(triptr->corner[0]);
pt2ptr=&(triptr->corner[1]);
pt3ptr=&(triptr->corner[2]);
pt3ptr->x=t3->x; etc etc
@H_489_0@解决方法
trilist
通过 realloc()
失效,因此您应该使用 tmp
进行移位。addtriangle(....):
应该是这样的:@H_674_3@
tmp = realloc(trilist,(@R_851_10586@ltri+1)*sizeof(trianglE));
for (int c = @R_851_10586@ltri; c > i; c--)
{
tmp[c] = tmp[c-1]; /* correctly shift the elements */
}
tmp[i] = new_value; /* assign new value (replace new_value with proper thing) */
trilist = tmp;
,
假设您有一个 p
类型的指针 T
,声明如下:T *p;
,并且您还有一个要添加的对象,声明为 T x;
@H_674_3@
然后就这样做:@H_674_3@
T *p = malloc(sizeof *p * sizE);
T x;
...
// Reallocate to make room for one more element
T *tmp = realloc(p,sizeof *p * (size + 1));
// Error checking
if(!tmp) { /* Handle error */ }
p = tmp;
// Move the elements after the insertion spot
memmove(&p[index+1],&p[index],sizeof *p * (size - indeX));
// And insert
p[index] = x;
如果您不关心在分配错误时恢复,则不需要临时变量。然后你可以这样做:@H_674_3@
p = realloc(p,sizeof *p * (size + 1));
if(!p) exit(EXIT_FAILURE);
,
tmp = (triangle *) realloc(trilist,(@R_851_10586@ltri+1)*sizeof(trianglE));
for (int c = @R_851_10586@ltri; c > i; c--)
{
trilist[c-1] = trilist[c];
在您的代码中修改(如果重新分配成功)无效指针。 trilist
可能未指向有效的内存位置。您应该改用 tmp
或将 trilist
分配给 tmp
。@H_674_3@
添加到数组的通用函数。@H_674_3@
void *addToArr(void *array,size_t arraysize,size_t pos,size_t elemsize,void *element)
{
unsigned char *ucarray;
array = realloc(array,(arraysize + 1) * elemsizE);
if(array)
{
ucarray = array;
memmove(ucarray + (pos + 1) * elemsize,ucarray + pos * elemsize,(arraysize - pos) * elemsizE);
memcpy(ucarray + pos * elemsize,element,elemsizE);
}
return array;
}
以上是大佬教程为你收集整理的将元素添加到 malloc 数组的中间全部内容,希望文章能够帮你解决将元素添加到 malloc 数组的中间所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。