簡體   English   中英

如何將內存重新分配給結構內的指針?

[英]How do I reallocate memory to a pointer inside a struct?

我需要為結構內的指針分配內存,但我不知道如何為struct Compra內的指針分配內存

struct Compra
{
    int id_cliente;
    float preco_final;
    int *id_artigos;
    int *conta_artigos;
    int receita;
    int dia;
    int mes;
    int ano;
};

void Alloc_Memoria_Pointers(struct Compra **compras, struct Contador **contadores, int incr)
{ 
    int *temp_a = NULL;
    int *temp_q = NULL;
    temp_a = (int*) realloc(*compras[0]->id_artigos, incr * sizeof(int));

    if(temp_a == NULL)
    {
        printf("Alocacao de memoria para id artigos falhada:(\n");
    }
    else
    {
        (*compras)[0].id_artigos = temp_a;
    }
}

正如評論中提到的,如果你只是想修改(重新分配)結構的一個成員,你只需要傳遞一個指向結構本身的指針,而不是一個指向結構的指針的指針。

就像是

struct Compra compra = { 0 };  // Initialize all member to "zero" or "null"
size_t new_size_of_artigos = 10;  // Example size

Alloc_Memoria_Pointers(&compra, new_size_of_artigos);

那么你的功能就可以很簡單

void Alloc_Memoria_Pointers(struct Compra *compra, size_t new_size)
{
    int *temp_a = NULL;

    // Reallocate (or allocate) the memory
    temp_a = realloc(compra->id_artigos, new_size * sizeof *temp_a);

    if (temp_a == NULL)
    {
        printf("Alocacao de memoria para id artigos falhada:(\n");
    }
    else
    {
        compra->id_artigos = temp_a;
    }
}

你可以做這樣的事情,

void Alloc_Memoria_Pointers(struct Compra **compras, struct Contador **contadores, int incr)
{
    struct Compra *local_ptr = *compras; //copy to a local pointer

    int *temp_a = NULL;
    temp_a = (int*)realloc(local_ptr->id_artigos, incr * sizeof(int));

    if (temp_a == NULL)
    {
        printf("Alocacao de memoria para id artigos falhada:(\n");
    }
    else
    {
        local_ptr->id_artigos = temp_a;
        printf("allocated");
    }
}

但是你需要傳遞一個指針的地址,

struct Compra *l1_ptr ;
Alloc_Memoria_Pointers(&l1_ptr,10);

暫無
暫無

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

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