[英]How to initialize a constant array of struct in another dynamically allocated struct
這是我的問題,我嘗試從結構初始化常量值,對於簡單的值,我這樣做: *(int*)&myStruct->myValue = 1;
它工作得很好,但是對於數組,我更願意使用類似的方法而不是“memcpy”,所以我這樣做了:
*(MyOtherStruct*)&myStruct->myArrayOfStructs = {
otherStruct1, otherStruct2,
otherStruct3, otherStruct4
};
但我得到了這個: error: expected expression before '{' token
而且我嘗試了很多東西,但要么完全是錯誤的,要么我有其他錯誤消息,我找不到編譯器想要的表達式並且可以正常工作......
之后,“memcpy”的使用可能是“有義務的”,但如果可能的話,如果沒有我的代碼,我會發現它會更好。
提前致謝 !
編輯:這是我想做的一個抽象但“有效”的例子。
#include <stdlib.h>
typedef struct {
int r, g, b, a;
} Color;
typedef struct {
const int value;
const Color color[4];
} structExample;
int main(void)
{
Color colorWhite = { 0, 0, 0, 255 };
Color colorBlack = { 255, 255, 255, 255 };
Color colorRed = { 255, 0, 0, 255 };
Color colorBlue = { 0, 0, 255, 255 };
structExample* myStruct = malloc(sizeof(structExample));
*(int*)&myStruct->value = 1;
*(Color*)&myStruct->color = {
colorWhite, colorBlack,
colorRed, colorBlue
};
return 0;
}
您不能分配 arrays。 您需要手動執行此操作
myStruct->myArrayOfStructs[0] = otherStruct1;
myStruct->myArrayOfStructs[1] = otherStruct2;
myStruct->myArrayOfStructs[2] = otherStruct3;
myStruct->myArrayOfStructs[3] = otherStruct4;
您不能分配一個數組,也不能分配一個數組的多個元素。 您可以分配數組的元素,您應該正確地進行轉換:
myStruct->color
是 4 Color
的數組。 獲取它的地址會產生一個Color (*)4
。 將其轉換為Color *
會導致技術違反 C 標准定義的行為所需的規則。const
。 所以簡單地取一個元素的地址而不是取數組的地址:* (Color *) &myStruct->color[0] = colorWhite;
* (Color *) &myStruct->color[1] = colorBlack;
* (Color *) &myStruct->color[2] = colorRed;
* (Color *) &myStruct->color[3] = colorBlue;
然而,這種對const
的拋棄使得避免違反 C 標准關於定義行為的規則變得令人厭煩。 更好的方法是:
structExample
的成員聲明中刪除const
。const
的結構。const
的新指針。執行此操作時,您還可以使用復合文字來初始化結構(即使它包含一個數組)。 這是一個例子:
#include <stdlib.h>
typedef struct
{
int r, g, b, a;
} Color;
typedef struct
{
int value;
Color color[4];
} structExample;
int main(void)
{
Color colorWhite = { 0, 0, 0, 255 };
Color colorBlack = { 255, 255, 255, 255 };
Color colorRed = { 255, 0, 0, 255 };
Color colorBlue = { 0, 0, 255, 255 };
// Start with pointer to non-const object.
structExample *myStruct = malloc(sizeof *myStruct);
// Assign initial value.
*myStruct =
(structExample) { 1, { colorWhite, colorBlack, colorRed, colorBlue } };
// Convert to pointer to const object.
const structExample *myStructConst = myStruct;
// Use pointer-to-const for further work.
extern void foo(const structExample *);
foo(myStructConst);
/* Inside foo, only the pointer-to-const is seen, so it will get a
diagnostic message if it attempts to modify the structure without
using an explicit cast. foo does not see the original myStruct
pointer.
*/
// Use the original pointer to free.
free(myStruct);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.