返回C struct数组

时间:2011-08-05 16:26:53

标签: objective-c c opengl

Hello stackoverflow成员吗?

A类结构声明

struct PointSprite 
{
    GLfloat x;
    GLfloat y;
    GLfloat size;
    Color4f color;
} ParticleSystems[MAXIMUM_PARTICLES_ON_SCREEN];
// I generally put some stuffs in ParticleSystem array. 
// for ex) struct PointSprite *ps = &ParticleSystems[index];
// and it works well on the class A, but I want to get class B to access this array.

我的问题是,我想如何返回' ParticlelSystems '数组的数组,以便其他类可以访问它?我试过下面的代码来返回指针,但是编译器给了我一个警告。

- (struct ParticleSystems *) commitParticles
{
    struct ParticleSystems *ptr = &ParticleSystems; // it said, assigning incompatible pointer type

    return ptr;
}

或者我应该分配' ParticleSystems '数组吗?请帮忙 !感谢

3 个答案:

答案 0 :(得分:2)

如果要在函数内部创建数组,则应使用new动态分配它,然后返回指向它的指针。

您无法从函数返回数组,您必须返回指向它的指针。

示例代码:

ParticleSystems* doSomethingInteresting()
{
    ParticleSystems *ptr = new ParticleSystems[MAXIMUM_PARTICLES_ON_SCREEN];

    //do the processing

    return ptr;

}

调用者获取返回的动态分配数组的所有权,需要释放它以避免内存泄漏:

delete []ptr;

答案 1 :(得分:2)

您可以在分配一个之后返回它,也可以填写用户传递给您的一个。后者使用户有责任向接收数据的方法提供ParticleSystem。它可以是本地数组,也可以是malloced数组。

- (void) commitParticles: (ParticleSystems *) sprites
{
    // set members of the structs here
}

我更喜欢这种传递来返回malloced数组。您的里程可能会有所不同。

答案 2 :(得分:0)

您收到了assigning incompatible pointer type编译器警告,因为您的ptr声明应该是PointSprite *类型,而不是ParticleSystems *