在 C 中直接初始化或分配变量数组的结构成员,并参考命名结构成员?



在SO和其他地方的类似问题中,在这种情况下讨论的唯一解决方案是使用数组符号初始化结构数组,而不是使用结构成员的点名。我最接近我想要的是以下代码:

int texturesCount = 2;
struct textureParams textures[texturesCount];
struct textureParams textures0 =   {
.textureFormat = textureFormat,
.textureAccess = textureAccess,
.srcrect = {.x = 0, .y = 0, .w = 50, .h = 50},
.dstrect = {.x = 0, .y = 500, .w = 50, .h = 50},
.r = 255,
.g = 0,
.b = 0,
.a = 0,
};
struct textureParams textures1 =   {
.textureFormat = textureFormat,
.textureAccess = textureAccess,
.srcrect = {.x = 0, .y = 0, .w = 20, .h = 20},
.dstrect = {.x = 10, .y = 100, .w = 20, .h = 20},
.r = 0,
.g = 255,
.b = 0,
.a = 0,
};
textures[0] = textures0;
textures[1] = textures1;

有没有办法做到这一点 - 使用命名结构成员创建数组的结构成员 - 但不创建临时变量texture0texture1

例如,如果您要创建一个int数组,则可以像这样初始化它:

int arr[3] = { 3, 4, 5 };

在您的情况下是相同的,只是它是一个结构数组,并且每个初始值设定项都是一个结构初始值设定项:

struct textureParams textures[texturesCount] = {
{
.textureFormat = textureFormat,
.textureAccess = textureAccess,
.srcrect = {.x = 0, .y = 0, .w = 50, .h = 50},
.dstrect = {.x = 0, .y = 500, .w = 50, .h = 50},
.r = 255,
.g = 0,
.b = 0,
.a = 0,
},
{
.textureFormat = textureFormat,
.textureAccess = textureAccess,
.srcrect = {.x = 0, .y = 0, .w = 20, .h = 20},
.dstrect = {.x = 10, .y = 100, .w = 20, .h = 20},
.r = 0,
.g = 255,
.b = 0,
.a = 0,
}
};

是的,您可以使用复合文字直接分配给数组的成员:

int texturesCount = 2;
struct textureParams textures[texturesCount];
textures[0] = (struct textureParams) {
.textureFormat = textureFormat,
.textureAccess = textureAccess,
.srcrect = {.x = 0, .y = 0, .w = 50, .h = 50},
.dstrect = {.x = 0, .y = 500, .w = 50, .h = 50},
.r = 255,
.g = 0,
.b = 0,
.a = 0,
};
textures[1] = (struct textureParams) {
.textureFormat = textureFormat,
.textureAccess = textureAccess,
.srcrect = {.x = 0, .y = 0, .w = 20, .h = 20},
.dstrect = {.x = 0, .y = 100, .w = 20, .h = 20},
.r = 0,
.g = 255,
.b = 0,
.a = 0,
};

最新更新