gpt4 book ai didi

c - 在其他文件中的结构/数组上使用 malloc

转载 作者:太空宇宙 更新时间:2023-11-04 07:51:53 25 4
gpt4 key购买 nike

更新:段错误的问题不在这个函数中,如下所述,它在同一程序的另一个函数中。

我正在尝试制作一个为弹跳球制作动画的程序,但是我被卡住了,无法弄清楚我做错了什么。我相信我已经将问题隔离在下面的函数中。我发现它与新模型语句有关。

无论如何,在运行代码时我得到了段错误并且函数绘制的值(根据三角形)超出了它们应该在的位置。我应该得到 0 到 1600 之间的值,但有时我最终会得到 9400 万。

非常感谢任何帮助!

object_t *create_object(SDL_Surface *surface, triangle_t *model, int numtriangles){
object_t *new=malloc(sizeof(object_t));
new->surface = surface;
new->model = malloc(sizeof(triangle_t)*numtriangles);
*new->model= *model;
new->numtriangles = numtriangles;
new->tx = surface->w/2;
new->ty = surface->h/2;
new->scale = 0.1;
new->rotation = 0.0;

return new;
}

注意! triangle_t *model 指针指向一个描述多个三角形的数组。

编辑:包括对象的结构:

typedef struct object object_t;

struct object {
float scale; /* Object scale */
float rotation; /* Object rotation */
float tx, ty; /* Position on screen */

float speedx, speedy; /* Object speed in x and y direction */
unsigned int ttl; /* Time till object should be removed from screen */

int numtriangles; /* Number of triangles in model */
triangle_t *model; /* Model triangle array */

SDL_Surface *surface; /* SDL screen */
};

三角形结构:

typedef struct triangle triangle_t;

struct triangle {
/* Model coordinates, where each pair resemble a corner */
int x1, y1;
int x2, y2;
int x3, y3;

/* The color the triangle is to be filled with */
unsigned int fillcolor;

/* Scale factor, meaning 0.5 should half the size, 1 keep, and 2.0 double */
float scale;

/* The point (tx, ty) where the center of the teapot should be placed on-screen */
int tx, ty;

/* The degrees the triangle is supposed to be rotated at the current frame */
float rotation;

/*
* Bounding box of on-screen coordinates:
* rect.x - x-coordinate of the bounding box' top left corner
* rect.y - y-coordinate of the bounding box' top left corner
* rect.w - width of the bounding box
* rect.h - height of the bounding box
*/
SDL_Rect rect;

/* On-screen coordinates, where each pair resemble a corner */
int sx1, sy1;
int sx2, sy2;
int sx3, sy3;
};

最佳答案

此行仅复制第一个三角形:

*new->model = *model;

从函数的角度来看,model 只是一个指向对象的指针。编译器不知道它指向一个三角形数组,因此我们需要将三角形的数量作为参数传递给它。

将其替换为:

memcpy( new->model, model, sizeof(triangle_t)*numtriangles);

补充说明:

  • 记得在释放对象时释放模型
  • 如果您考虑使用 C++ 编译器编译它,请将 new 替换为 newObj 之类的东西

更多信息:

[编辑]关于段错误:你的函数现在是正确的,它不会导致 SEGFAULT 除非你内存不足,这是不太可能的。无论如何,如果内存不足并在该函数中出现 SEGFAULT,那么问题可能是:

  • 你没有在其他地方正确地释放内存,然后你有内存泄漏导致你不正确地耗尽内存。
  • 您的平台需要更多内存,尽管不太可能,但这是可能的,尤其是当它是一个有限的嵌入式平台时

发布另一个关于段错误回溯的问题。

关于c - 在其他文件中的结构/数组上使用 malloc,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53267814/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com