c - 如何使用指向 C 中结构数组的指针为结构分配内存?

标签 c arrays struct nested dynamic-memory-allocation

我有一个函数可以为列表创建并返回一个新对象,但我在分配内存时遇到了问题(错误:核心转储)。我认为这是因为“*模型”,它是指向结构数组的指针。我对动态内存分配很陌生,不确定分配什么以及如何分配合适的内存量。

功能:

// Return a newly created object based on the arguments provided. 
object_t *create_object(SDL_Surface *surface, triangle_t *model, int numtriangles)
{
    // Allocate memory for a new object
    object_t *new_obj = malloc(sizeof(object_t));
        if (new_obj == NULL)
            return NULL;
    // Allocate memory for the model array
    triangle_t *arrayPtr = malloc((sizeof(triangle_t))*numtriangles);
        if (arrayPtr == NULL)
            return NULL;

    // Assign values
    arrayPtr = model;
    new_obj->model = arrayPtr;
    new_obj->numtriangles = numtriangles;
    new_obj->surface = surface;
    // Return created object
    return new_obj;
}

主函数调用:

object_t *ball = create_object(surface, sphere_model, SPHERE_NUMTRIANGLES);

结构:

typedef struct object object_t;
struct object {
    float       scale;
    float       rotation;
    float       tx, ty;
    float       speedx, speedy;
    unsigned int ttl;          
    int         numtriangles;
    triangle_t  *model;
    SDL_Surface *surface;
};

typedef struct triangle triangle_t;
struct triangle {
    int x1, y1;
    int x2, y2;
    int x3, y3;
    unsigned int fillcolor;
    float scale;
    int tx, ty;
    float rotation;
    SDL_Rect rect;
    int sx1, sy1;
    int sx2, sy2;
    int sx3, sy3;
};

数组:

#define SPHERE_NUMTRIANGLES    478   // <-- Array size
triangle_t sphere_model[] = {
{
.x1=-1,
.y1=-500,
.x2=-1,
.y2=-489,
.x3=-1,
.y3=-500,
.fillcolor=0xeeeeee,
.scale=1.0
},
{
.x1=-1,
.y1=-489,
.x2=-1,
.y2=-500,
.x3=40,
.y3=-489,
.fillcolor=0xbb0000,
.scale=1.0
},
...

我尝试了 object_t *new_obj = malloc(sizeof(object_t) + (sizeof(triangle_t)*numtriangles)); 但没有成功。

最佳答案

// Assign values
arrayPtr = model;

你在这里所做的是丢弃包含在 arrayPtr 中的新分配的指针,并将其分配给指向与 model 相同的内存。如果 model 的生命周期较短(例如分配在堆栈上)并且在函数返回后不再是有效指针,它可能会崩溃。

我相信您的意图是将模型数组中的内容复制到您的新数组中,因此您应该做类似的事情:

memcpy(arrayPtr, model, (sizeof(triangle_t))*numtriangles);

关于c - 如何使用指向 C 中结构数组的指针为结构分配内存?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53222588/

相关文章:

c - 如何在使用介子构建的 C 项目中使用 OpenMP

c - 指针歧义

arrays - 将值放入带有数组数据的字典中 - swift

c++ - uint12 结构中的字节顺序

通过 typedefs 的 C11 匿名结构?

c - Printf 让程序卡住没有响应

c - 如何创建一个写入 FILE * 的库,而不是将数据写入内存? (C 编程)

c - 这个迭代的汉诺塔是如何工作的? C

php - 如何仅回显我的 $row 的索引

swift - Struct 不符合 RawRepresentable 协议(protocol)?