I cannot print, in the main function, values from a vector created in another function received by a double pointer

Asked

Viewed 37 times

3

The following source code is the miniaturization of a larger problem I’ve been working on for two days that I can’t solve the problem.

I need to print the values of the vector generated by the "fazVetor" function, in the "main" function".

However, in order for the code to resemble the real problem I am working on, there are two restrictions that must be respected. These are commented in the following code.

#include <stdio.h>
#include <stdlib.h>
#define TAM 3

int fazVetor(int **vet){
    int *array = malloc(sizeof(int) * TAM);

    array[0] = 4;
    array[1] = 7;
    array[2] = 8;

    /* nesta função somente a linha a seguir PODE ser alterada. */
    *vet = array;
}

int main()
{
    int **qq;

    /* Na função main, somente a linha a seguir NÃO PODE ser alterada. */
    fazVetor(&qq);

    printf("\n--==[Valores do Vetor]==--\n\n");
    for(int i = 0; i < TAM; i++){
        printf(" %d", (qq[i]));
    }

    printf("\n\n");
    return 0;
}

The above code works, but not in the way it should. That is, I cannot print the three values of the vector. If anything, I can print out memory addresses.

If anyone can help, it will be of great value!

  • Which lines can be changed ? The function signature does not play with the type passed. fazVetor(&qq) does not play with int fazVetor(int **vet){ and one of them will have to be changed.

1 answer

4


In function main, the variable qq is declared as double pointer and when calling function fazVetor() with the operator &qq, generates a triple pointer.

As the function fazVetor() receives a double pointer, this generates the error when printing the vector content.

The solution is to change the variable declaration qq for single pointer (with only one *):

int *qq;

After this change, the result is printed correctly:

--==[Valores do Vetor]==--

 4 7 8
  • 1

    Excellent! Thank you very much!

Browser other questions tagged

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