You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何从C函数返回对象数组?附SDL_Vertex实现示例

从C函数返回对象数组的几种可行方案

你的代码存在核心问题:函数返回的是局部数组triangleVertex的地址,但局部数组在函数执行结束后会被销毁,返回它会导致未定义行为。下面是几种实现你需求的正确方式:

方案1:让调用者提供目标数组,函数负责填充内容

这是最安全、最常用的方式,完全避免内存管理问题:

void initTriangle(SDL_Vertex* outVertices, struct Point2D point1, struct Point2D point2, struct Point2D point3) {
    outVertices[0] = (SDL_Vertex){
        { point1.x, point1.y },
        { 255, 255, 0, 0xFF },
        { 0.f, 0.f }
    };
    outVertices[1] = (SDL_Vertex){
        { point2.x, point2.y },
        { 0, 255, 255, 0xFF },
        { 0.f, 0.f }
    };
    outVertices[2] = (SDL_Vertex){
        { point3.x, point3.y },
        { 255, 0, 255, 0xFF },
        { 0.f, 0.f }
    };
}

// 使用方式
SDL_Vertex triangleVertex[3];
initTriangle(triangleVertex, p1, p2, p3);
SDL_RenderGeometry(renderer, NULL, triangleVertex, 3, NULL, 0);

方案2:返回动态分配的数组指针

需要注意调用者必须手动释放内存,避免内存泄漏:

SDL_Vertex* initTriangle(struct Point2D point1, struct Point2D point2, struct Point2D point3) {
    SDL_Vertex* vertices = malloc(3 * sizeof(SDL_Vertex));
    if (!vertices) {
        // 处理内存分配失败的情况
        return NULL;
    }
    vertices[0] = (SDL_Vertex){
        { point1.x, point1.y },
        { 255, 255, 0, 0xFF },
        { 0.f, 0.f }
    };
    vertices[1] = (SDL_Vertex){
        { point2.x, point2.y },
        { 0, 255, 255, 0xFF },
        { 0.f, 0.f }
    };
    vertices[2] = (SDL_Vertex){
        { point3.x, point3.y },
        { 255, 0, 255, 0xFF },
        { 0.f, 0.f }
    };
    return vertices;
}

// 使用方式
SDL_Vertex* triangleVertex = initTriangle(p1, p2, p3);
if (triangleVertex) {
    SDL_RenderGeometry(renderer, NULL, triangleVertex, 3, NULL, 0);
    free(triangleVertex); // 必须手动释放内存
}

方案3:用结构体包裹数组,返回结构体

C语言允许直接返回结构体,这样可以实现类似"返回数组"的直观效果:

// 定义包含SDL_Vertex数组的结构体
typedef struct {
    SDL_Vertex vertices[3];
} TriangleVertices;

TriangleVertices initTriangle(struct Point2D point1, struct Point2D point2, struct Point2D point3) {
    return (TriangleVertices){
        .vertices = {
            {
                { point1.x, point1.y },
                { 255, 255, 0, 0xFF },
                { 0.f, 0.f }
            },
            {
                { point2.x, point2.y },
                { 0, 255, 255, 0xFF },
                { 0.f, 0.f }
            },
            {
                { point3.x, point3.y },
                { 255, 0, 255, 0xFF },
                { 0.f, 0.f }
            }
        }
    };
}

// 使用方式
TriangleVertices triangle = initTriangle(p1, p2, p3);
SDL_RenderGeometry(renderer, NULL, triangle.vertices, 3, NULL, 0);

方案对比

  • 方案1:无需内存管理,性能最优,推荐优先使用
  • 方案2:灵活但需要手动管理内存,适合数组长度不固定的场景
  • 方案3:语法最接近你的需求,但会有结构体复制的开销(对于3个元素的数组可忽略)

内容的提问来源于stack exchange,提问作者spots 727

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.20 17:57:06