我试图在main中创建一个纹理数组,然后将其传递给函数以供使用。
我不知道将指针传递给此数组的正确方法,或者我是否写错了数组。
[为了增加一层混乱,我读到我正在使用的数据类型SDL_Texture需要一个双指针,因为它的内容只能由库在内部访问。
总之,有人可以告诉我创建和传递此数据类型的数组的正确语法。
测试代码:
#include <SDL.h>
#include <SDL_image.h>
//function that places array of textures across top of window
void processTexture(SDL_Renderer *renderer,
int arElements,
SDL_Texture *textureArray //correct pointer?
)
{
for(int i = 0; i < arElements; ++i)
{
SDL_Rect textureRect = {i*10, 0, 10, 10}; //rectangle for placing textures
//problem area?
SDL_RenderCopy(renderer,
*textureArray[i], //correct pointer?
NULL,
textureRect
);
}
}
int main(int argc, char *argv[])
{
//set up, ignore this
SDL_Init(SDL_INIT_VIDEO);
IMG_Init(IMG_INIT_PNG);
SDL_Window *window = SDL_CreateWindow("test",
SDL_WINDOWPOS_UNDEFINED,
SDL_WINDOWPOS_UNDEFINED,
100,
100,
0
);
SDL_Renderer *renderer = SDL_CreateRenderer(window,
-1,
0
);
SDL_Surface *surface = IMG_Load("test.png");
SDL_Texture *testTexture = SDL_CreateTextureFromSurface(renderer, surface);
SDL_FreeSurface(surface);
//create single element test array, also problem area?
int arElements = 1; //number of textures to place in array
SDL_Texture textureArray[arElements]; //array of data type SDL_Texture with arElements number of elements. correct syntax?
textureArray[0] = *testTexture; //array element contains pointer to texture. correct syntax?
//call function that uses array of textures
processTexture(renderer,
arElements,
&textureArray //correct pointer?
);
//clean up, ignore this
IMG_Quit();
SDL_DestroyRenderer(renderer);
SDL_DestroyWindow(window);
SDL_Quit();
return 0;
}
错误:
In function 'processTexture':|
17|error: invalid use of undefined type 'struct SDL_Texture'|
17|error: dereferencing pointer to incomplete type 'SDL_Texture {aka struct SDL_Texture}'|
19|error: incompatible type for argument 4 of 'SDL_RenderCopy'|
870|note: expected 'const SDL_Rect * {aka const struct SDL_Rect *}' but argument is of type 'SDL_Rect {aka struct SDL_Rect}'|
In function 'SDL_main':|
48|error: array type has incomplete element type 'SDL_Texture {aka struct SDL_Texture}'|
48|warning: unused variable 'textureArray' [-Wunused-variable]|
任何建议将不胜感激
您的数组类型错误。 SDL使用不透明类型,因此您不能仅通过指针通过值保存它们(或取消引用它们的指针,同样的事情)。
SDL_Texture textureArray[arElements]
应该是
SDL_Texture*
的数组。
您在从那里传递指向您自己的函数和SDL的指针时遇到问题。
//call function that uses array of textures processTexture(renderer, arElements, &textureArray //correct pointer? );
&textureArray
是指向整个数组的指针,但是您的函数需要一个指向第一个元素的指针。写&textureArray[0]
,或者只写textureArray
,并用衰减指针处理它。
//problem area? SDL_RenderCopy(renderer, *textureArray[i], //correct pointer? NULL, textureRect );
请勿将
*textureArray[i]
传递给SDL,因为它是不透明的类型,所以您不能取消引用它。只需传递textureArray[i]
,即textureArray + i
,即指向第i
个元素的指针即可。