我有一个函数,它将 3D 空间中的一个点 append 到数组的末尾,然后计算 append 每个点所需的时间。但是当我运行我的代码时,它创建了一个初始化代码。但是当它试图运行函数 append 时,它立即出现了错误。我一直在查看我的代码,但我无法弄清楚为什么它会出现段错误。谁能帮帮我?
这是我的追加代码:
int point_array_append( point_array_t* pa, point_t* p)
{
assert( pa );
assert( p );
if( pa->len < pa->reserved )
{
size_t new_res = pa->len * 2 + 1; // add 1 to take care of a NULL array
size_t sz= new_res * sizeof(point_t);
point_t* tmp = realloc( pa->points, sz );
if( tmp == 0 )
return 1; //fail
pa->points = tmp;
pa->reserved = new_res;
}
pa->points[pa->len] = *p; // copy struct into array
pa->len++;
return 0;
}
这是我使用的两个结构:
typedef struct point
{
double x, y, z; // location in 3D space
} point_t;
typedef struct
{
size_t len; // number of points in the array
point_t* points; // an array of len point_t structs
size_t reserved;
} point_array_t;
最佳答案
可能你在 if 条件中有一个错误:
if( pa->len < pa->reserved )
你可能想要的是:
if ( <there are no more free slots in the array> ) reallocate
转化为:
if (pa->len >= pa->reserved)
... do the reallocation
关于c - 尝试将 3D 空间中的点 append 到数组末尾时出现段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27167756/