C 结构中的两个数组
C Two Arrays in Struct
我想创建一个包含 2 个数组的结构,并且我希望用户指定它们包含的变量数量。但是当我 运行 this:
时出现错误
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;
创建结构对象时,知道实际大小 ("amount"),然后动态分配内存:
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 中未被授权。
大小必须在编译时知道。
你在这里应该做的是
typedef struct Image
{
int amount;
char** paths;
SDL_Texture** textures;
} Image;
Image* img = (Image*)malloc(sizeof(Image));
img->amount = 42;
img->paths = (char**)malloc(sizeof(char*) * img->amount);
img->textures = (SDL_Texture**)malloc(sizeof(SDL_Texture*) * img->amount);
我想创建一个包含 2 个数组的结构,并且我希望用户指定它们包含的变量数量。但是当我 运行 this:
时出现错误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;
创建结构对象时,知道实际大小 ("amount"),然后动态分配内存:
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 中未被授权。 大小必须在编译时知道。
你在这里应该做的是
typedef struct Image
{
int amount;
char** paths;
SDL_Texture** textures;
} Image;
Image* img = (Image*)malloc(sizeof(Image));
img->amount = 42;
img->paths = (char**)malloc(sizeof(char*) * img->amount);
img->textures = (SDL_Texture**)malloc(sizeof(SDL_Texture*) * img->amount);