How to dynamically increase struct size?

Asked

Viewed 582 times

2

How to increase the size of struct when the current size is reached?

#define TAM_MAX 50;
typedef struct{
char nome[TAM_NOME];            /* nao pode ser vazio*/
char sobrenome[TAM_SOBRENOME];
char telefone[3][TAM_FONE];     /* modelo: '+99 (99) 9 9999 9999' */
char email[3][TAM_EMAIL];       /* 'modelo: a-z . _ 0-9 @ a-z . a-z . a-z' */
} TCONTATO;
TCONTATO agenda[TAM_MAX];

3 answers

2


The size of struct is not possible. What it seems you are wanting is to increase the size of the array. Also not dynamically, created, stays that size.

What you can do is allocate heap a sufficient amount of bytes to store the amount of objects you want (malloc()) and if you reach the border relocate (realloc()). This way you will have a pointer generated by the allocation function creating an indirect.

I have already answered something about Dynamic allocation for struct, Segmentation fault error (core dumped) and Problem with dynamic allocation. May also be useful: Problems with dynamic allocation

May be useful: This prevents an array from being initialized with a variable size in C?. A question has already been asked about allocation: What is the purpose of the free function()?.

And there’s nothing wrong with the statement by struct.

0

One thing you can do is store only pointers in your struct

typedef struct{
    char *nome;
    char *sobrenome;
    size_t num_telefones;
    char **telefones;
    size_t num_emails;
    char **emails;
} TCONTATO;

If you do this, you will need to allocate space for these fields separately. It’s more complicated than the version you make now, where memory is always inside the struct, but it’s more flexible.

-1

Your struct statement is incorrect, the correct form would be:

typedef struct myStruct{ //myStruct é o nome da struct declarada

The safest way to dynamically increase items within a struct is to create that same struct with abstract data types (TAD). It is not possible to increase the size of an item of a struct if the same item is of a primitive type like int, char, float or double, to dynamically increase it it needs to be an abstract type of data like a Stack, Queue or List, detail what abstract types of data(TAD) are part of a slightly more advanced content of C programming, notoriously you need to master the language with ease to be able to implement them.

  • What’s wrong with the statement?

  • I refer to the statement of struct for use in a TAD.

  • 1

    His typedef is correct. You just have to do struct myStruct { when your struct type is recursive.

  • Precisely, a struct for TAD

  • typedef struct myStruct{
 int value;
 int index;
 struct myStruct *front, *back; //próxima struct e anterior
}Index; //Lista duplamente encadeada

Browser other questions tagged

You are not signed in. Login or sign up in order to post.