簡體   English   中英

使用C中的字符指針為結構分配內存

[英]Allocate memory for a struct with a character pointer in C

我今天很難修復代碼,然后我遇到類似的東西:

typedef struct {
int a; 
int b; 
int c;
int d;
char* word;
} mystruct;

int main(int argc, char **argv){

    mystruct* structptr = malloc(sizeof(mystruct));
    if (structptr==NULL) {
        printf("ERROR!")
        ...
    }
    ...
    free(structptr);

    return 0;
}

由於char* word是一個可變長度的字符串,而且malloc沒有為它分配足夠的內存,因此代碼提供了大量的內存錯誤。 實際上它只為整個struct分配了20 Bytes 有沒有辦法繞過這個問題,而不是將char*變成像char word[50]

您只為結構本身分配內存。 這包括指向char的指針,它在32位系統上只有4個字節,因為它是結構的一部分。 它不包含未知長度的字符串的內存,因此如果您想要一個字符串,您還必須手動為其分配內存。 如果您只是復制字符串,則可以使用strdup()來分配和復制字符串。 你仍然必須自己釋放內存。

 mystruct* structptr = malloc(sizeof(mystruct));
 structptr->word = malloc(mystringlength+1);

 ....

 free(structptr->word);
 free(structptr);

如果您不想自己為字符串分配內存,那么您唯一的選擇是在結構中聲明一個固定長度的數組。 然后它將成為結構的一部分,而sizeof(mystruct)將包含它。 如果這適用與否,取決於您的設計。

word所需的長度(N)添加第二個malloc

   mystruct* structptr = malloc(sizeof(mystruct));

   structptr->word = malloc(sizeof(char) * N);

你可以在這里閱讀你需要分別分配char *

mystruct* structptr = malloc(sizeof(mystruct));
structptr->word = malloc(sizeof(WhatSizeYouWant));

當您分配內存structptr ,指針wordstruct沒有有效的記憶點。 讓你無論是malloc一塊內存的word ,也還是讓word點到另一個角色。

malloc外部struct只分配*word指向的1字節內存,因為它是'char *'類型。 如果要分配超過1個字節的內存word ,有2個選項:

  1. 就像你說的那樣,把它聲明為char word[50]而不是`char *'
  2. malloc / calloc(我個人更喜歡calloc,省去了zeromemory的麻煩,這是非常重要的..)外部結構,然后malloc / calloc也是內部word 在這種情況下,請記得兩次free通話。

使用word=malloc(128);

這將為您的可變單詞分配128個字節,

暫無
暫無

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

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