簡體   English   中英

使用malloc在struct中設置指針數組的問題

[英]Problem with setting the array of pointers in the struct using malloc

我想為 struct 中的指針數組分配內存,但收到以下錯誤:

表達式必須是可修改的左值

這是結構代碼:

typedef struct {
    int id;
    char *entity[];
}entity;

這是 main 函數中的內存分配:

entity s;
s.entity= malloc(30 * sizeof(char *));

IDE 在 s.entity 下划線並彈出我提到的錯誤。

請幫我解決這個問題。

您的結構沒有名為entity的成員,只有idset

您顯然想分配整個結構。 如果您想在一個malloc分配整個結構,這種稱為靈活數組成員的結構成員非常有用。

entity *s;
s = malloc(sizeof(*s) + 30 * sizeof(s -> set[0]));

這種結構成員非常有用,因為您可以在一次調用中重新reallocfree它們。

set數組的大小增加到50

entity *tmp = realloc(s, sizeof(*s) + 50 * sizeof(s -> set[0]));
if(tmp) s = tmp;

這就是您分配指針的方式:

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'
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM