c - 尝试将 3D 空间中的点 append 到数组末尾时出现段错误

标签 c arrays segmentation-fault append points

我有一个函数,它将 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/

相关文章:

c - 什么时候结构没有填充?

java - 应用 Array.sort() 函数后数组元素变为 0

javascript - 从数组中分离并附加值

java - 创建类存储对象

c - 在 c 中释放 char 指针会导致段错误

我可以从 C 中的变量中检索数据类型吗?

c++ - 有没有办法不等待 system() 命令完成? (在三)

c - 在C中传输文件

c - 段错误打开文件

c - 包含 glad.h 时出现段错误