Pointer pointer in C

Asked

Viewed 36 times

0

Come on, guys, I’m trying to understand the pointer-pointer behavior, but I can’t figure it out. Well, I already have an idea that the pointer points the memory address of something, to another location, thus facilitating the use, but when I create a pointer pointer, everything is already confused.

Follow the example, the idea is to create items to dynamically allocate in the Map, but I can’t understand how the "**list" will group several allocations of different items? And how I can query the address of each item?

typedef struct _item
{
    int conta; //contador
    char *termo; //palavra
} Item;

typedef struct _mapa
{
    int total; // número de itens no mapa
    int blocos; // número de blocos de itens alocados
    Item **lista; // vetor de ponteiros para itens
} Mapa;void 

I even tried to create a way to allocate a new item, but because I didn’t understand the **list behavior, I couldn’t locate the location to add the new allocation. **list becomes a kind of Matrix?

insere_termo (Mapa *mp, char *s)
{
    Item * it = malloc (sizeof(Item));
    it->termo = s;
    it->conta = 1;

    mp->lista = ⁢
}
  • If you will place more than one item mp->lista, you first need to allocate memory to mp->lista, saying how many elements you intend to allocate, something like mp->lista = calloc(x, sizeof(*mp->lista)), where x is the amount of elements allocated, then you can insert into the list using array notation, something like: mp->lista[i] = item, where i is the Indian. And detail, unless you have consulted the C specifications in the ISO and are very sure of what you are doing, never get the name of a namesake with _, as in _item and _mapa.

  • I knew, I would then have to allocate X times the list to use it as a vector, so because it’s a static allocation, I can go through it like an indexed vector, all without changing the two structures I gave as an example right?

  • Actually, the way I said the allocation would be dynamic, not static. If you want static allocation, you would have to change the Map struct and declare the item as Item *lista[x].

No answers

Browser other questions tagged

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