What is pointer to pointer?

12

How should you use pointer to pointer ? I have a hard time distinguishing what is memory address and value in memory when I try to use pointer to pointer, this seems mysterious to me. Could someone give me an explanation and an example of using pointer to pointer ?

My attempt to implement pointer to pointer :

#include <stdio.h>

int main(void)
{
    //Este código gera um erro. E não exibe o valor da variável "ponteiroDoPonteiro".

    int *ponteiro, **ponteiroDoPonteiro, valor;

    valor = 50;
    ponteiro = &valor;

    *ponteiroDoPonteiro = &ponteiro;

    printf("\n%d", **ponteiroDoPonteiro);

    return 0;
}
    
asked by anonymous 16.10.2015 / 18:32

2 answers

9

The error has already been pointed out by the mgibsonbr comment. You can not store an address (when using & is telling to get the address) as a pointer value. You put the address in the pointer itself (remember that *variavel is saying that it wants the value pointed to by the pointer).

#include <stdio.h>

int main(void) {
    int *ponteiro, **ponteiroDoPonteiro, valor;
    valor = 50;
    ponteiro = &valor;
    ponteiroDoPonteiro = &ponteiro; //note que a variável realmente já é um ponteiro
//o que está na posição da memória apontada pela posição da memória de ponteiroDoPonteiro
    printf("\n%d", **ponteiroDoPonteiro);
    return 0;
}

See working on ideone .

The pointer pointer is widely used in vectors where it simulates multiple dimensions, but the most common use is in simulating a vector of strings . If the string concept existed in the language and the array was treated somewhat differently, pointer pointer use cases would be rare.

Obviously it can have more levels, but it is rarer to find application for it.

I think the details can be found in another response here on the site which links to the other one in the OS.     

16.10.2015 / 18:49
7

A pointer is a variable that holds the memory address of another variable, both of the same type.

A pointer to a pointer consists of a variable that holds the address of another, which in turn saves the address of the variable that has a "common" data type.

Inpracticetheconceptcanbeseenasfollows:

#include<stdio.h>intmain(void){int*ponteiro,**ponteiroDoPonteiro,valor;valor=50;ponteiro=&valor;ponteiroDoPonteiro=&ponteiro;printf("\nValor de ponteiroDoPonteiro: %p\nEndereço de memoria de ponteiro: %p\nValor de ponteiro: %p\nEndereco de memoria de valor: %p\nValor: %d", ponteiroDoPonteiro, &ponteiro, ponteiro, &valor, valor);
    return 0;
}

The code problem has already been pointed out twice in the comment and in the response, when trying to *ponteiroDoPonteiro = &ponteiro; you are trying to put the ponteiro address in the value of ponteiroDoPonteiro , which does not exist if it does not point to anything.

Take out * that you will succeed.

    
16.10.2015 / 19:00