How to dynamically increase the struct size?

2

How can I increase the size of the 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];
    
asked by anonymous 06.11.2016 / 17:31

3 answers

2

struct is not possible. What you seem to want is to increase the size of the array . Neither does it dynamically. Created, it's that size.

What you can do is to allocate in the heap a sufficient number of bytes to store the number of objects you want ( malloc() ) and if you reach the realloc limit ( realloc() ). This will have a pointer generated by the allocation function creating an indirection.

I already answered something about it in Dynamic allocation for struct , Error Segmentation fault (core dumped) and Dynamic Allocation Problem . It can also be useful: Dynamic allocation issues

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

And there's nothing wrong with declaring struct .

    
06.11.2016 / 18:03
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 within the struct, but it's more flexible.

    
06.11.2016 / 20:34
-1

Your struct declaration 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 the same struct with abstract data types (TAD). It is not possible to increase the size of an item in a struct if the same item is of a primitive type such as int, char, float or double, to dynamically increase it it must be an abstract type of data such as a Stack, Queue, or List , note that abstract data types (TAD) are part of a slightly more advanced content of C programming, notoriously you need to easily master the language in order to implement them.

    
06.11.2016 / 17:57