我想為 struct 中的指標陣列分配記憶體,但收到以下錯誤:
運算式必須是可修改的左值
這是結構代碼:
typedef struct {
int id;
char *entity[];
}entity;
這是 main 函式中的記憶體分配:
entity s;
s.entity= malloc(30 * sizeof(char *));
IDE 在 s.entity 下劃線并彈出我提到的錯誤。
請幫我解決這個問題。
uj5u.com熱心網友回復:
您的結構沒有名為 的成員entity,只有id和set。
您顯然想分配整個結構。如果您想將整個結構分配到一個中,這種稱為靈活陣列成員的結構成員非常有用malloc。
entity *s;
s = malloc(sizeof(*s) 30 * sizeof(s -> set[0]));
這種結構成員的是,你可以非常有用的realloc或者free他們在一個單一的呼叫。
將set陣列的大小增加到50
entity *tmp = realloc(s, sizeof(*s) 50 * sizeof(s -> set[0]));
if(tmp) s = tmp;
uj5u.com熱心網友回復:
這就是您分配指標的方式:
typedef struct {
int id;
char **set;
}entity;
int how_many_pointers = 30;
entity s;
s.set= malloc(how_many_pointers * sizeof(char *));
對于每個指標,您必須為相應的字串分配空間:
int i, string_size;
for(i = 0; i < how_many_pointers; i )
{
printf("How many chars should have string number %d ?", i 1);
scanf("%d", &string_size);
s.set[i] = malloc((string_size 1) * sizeof(char)); // string 1 due to space for '\0'
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/360380.html
下一篇:將二維陣列作為C 中的方法列印
