Create list chained with realloc ()

0

I need to implement a list that is simply chained that does not have an indication of next, that is, it should work as a vector, accessing nearby positions in memory. I am using the realloc () command to try to implement, however I am getting error when I am going to access any of the items in the list.

Struct that I'm using:

    typedef struct Lista lista;

    struct Lista {
    char nome[81];
    char telefone[15];
    char celular[15];
    char endereco[101];
    };

Function to insert in the list:

void insererealloc(lista **l, int t)
{
    *l = (lista*) realloc(*l, (t)*sizeof(lista));

    setbuf(stdin, NULL);

    printf("Digite o nome");
    gets((*l)->nome);

    setbuf(stdin, NULL);

    printf("Digite o telefone");
    gets((*l)->telefone);

    setbuf(stdin, NULL);

    printf("Digite o celular");
    gets((*l)->celular);

    setbuf(stdin, NULL);

    printf("Digite o endereco");
    gets((*l)->endereco);

    setbuf(stdin, NULL);
}
All right until then! The problem occurs when I try to "start" the elements of the list, I am accessing them as a pointer, for example: list [i] -> name, where i is any position. What is the correct way to access these members?

NOTE: I know that gets () is not at all reliable, though I'm just testing and I'm a little lazy to use fgets () or something better.

    
asked by anonymous 29.09.2015 / 03:57

2 answers

0

Good first one touch to make your code more readable. When working with struct and allocating them dynamically it is always more interesting to put typedef as being a pointer, for example:

typedef struct Lista *lista;

So when you refer to the pointer created with type lista , it will already become a pointer without needing the millions of *.

The most appropriate function for you to do this type of writing in a struct is undoubtedly getline and fgets . But be careful, fgets can generate buffer overflows that are due to the character '\ n' that is supposed to be placed in the vector of characters, I always put +1 space on the vectors.

The main problem with gets is that you have no control over how many bytes will be used or placed by the user. This can cause serious overflow problems.

Use the tips I've given and probably your headaches with readings of character vectors and structs will be lighter.

=)

    
14.10.2015 / 22:42
0

When you take the position of a pointer it stops being a pointer. ex:

lista *l;
for(in=0;i<n;i++)
    puts(l[i]->nome); // isso vai dar erro

    puts(l[i].nome); // isso não vai dar erro

or

lista **l;
for(in=0;i<n;i++)
    puts(l[i]->nome); // isso não vai dar erro

    puts(l[i].nome); // isso vai dar erro

This depends on whether it is a double or a simple pointer, if it is simple, use [i]. and not [i]->

    
21.02.2016 / 05:00