我想创建一个包含 2 个数组的结构,并且我希望用户指定它们包含的变量数量。但是当我运行它时出现错误:
typedef struct Image
{
int amount;
char* paths[amount];
SDL_Texture* textures[amount];
} Image;
为什么会出现错误,我该如何解决?
最佳答案
要拥有动态数组,您需要指针:
typedef struct Image
{
int amount;
char** paths; // pointer to pointer of chars
SDL_Texture** textures; // pointer to pointer of textures
} Image;
当你创建一个结构对象时,知道实际大小(“数量”)然后动态分配内存:
struct Image img;
img.paths = calloc (amount, sizeof(char*));
img.textures = calloc (amount, sizeof(SDL_Texture*));
img.amount = amount;
当然,你需要检查分配的指针不为NULL。
然后您可以像访问您自己的结构一样访问这些项目。
备注:变长数组是C11标准的可选特性。并非每个编译器都支持它。但在任何情况下,typedef
都不允许使用可变长度数组,因为 C 编译器需要在编译时知道整个 struct
的大小。这只有在数组大小为常量时才有可能。
关于C 结构中的两个数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28787807/