我有一个结构,并在其中指向2D数组.但是当我尝试将一个实际的2D数组分配给该指针时,我没有成功 - 编译器说我的指针是指向一维数组的指针.
这是我的代码:
typedef GLfloat Vertex2f[2];
typedef GLfloat TextureCoordinate[2];
typedef struct {
GLuint texture_name; // OpenGL ID of texture used for this sprite
Vertex2f *vertices; // array of vertices
TextureCoordinate *texture_coords; // texture vertices to match
GLubyte *vertex_indices;
} game_sprite;
void loadState()
{
game_sprite ballSprite;
createAndLoadTexture("ball.png", &ballSprite.texture_name);
const Vertex2f tempVerticesArray[4] = {
{-100.0f, -100.0f},
{-100.0f, 100.0f},
{100.0f, 100.0f},
{100.0f, -100.0f}
};
ballSprite.vertices = &tempVerticesArray; //The problem appears to be here
}
Run Code Online (Sandbox Code Playgroud)
我怎样才能使它工作?
谢谢.
你有两个问题.首先tempVerticesArray是const.您不能在没有类型转换的情况下将指向const值(&tempVerticesArray)的指针指定给指向非const变量(ballSprite.vertices)的指针,因此编译器会抱怨.您应该将vertices数据成员修改为类型const Vertex2f *,假设您实际上并未实际修改该数据.
第二个问题是,一旦loadState()结束,变量tempVerticesArray就会超出范围,因此任何悬挂指针(具体而言ballSprite.vertices)都是无效的.你应该创建tempVerticesArray一个static变量,因此它不是一个超出范围的堆栈变量.这假设ballSprite在该函数结束后使用该对象,我猜它是基于上下文做的.
如果确实需要在初始化后修改顶点,则需要为每个ballSprite顶点数据集合分配(例如使用malloc())并复制顶点数据(例如使用memcpy()).如果不这样做,所有ballSprite实例将共享指向相同顶点数据的指针,当您修改它们时,它们都将受到影响.
| 归档时间: |
|
| 查看次数: |
299 次 |
| 最近记录: |