0

I'm with a situation similar to this:

#include <stdio.h>
#include <stdlib.h>

void madeVector(int **occurr){
    int vector[] = { 1, 2, 3, 4, 5};
    int *pOccurr;

    pOccurr = vector;
    occurr = &pOccurr;

    printf("\n--==[Inside Function]==--\n\n");
    for(int i = 0; i < 5; i++){
        printf(" %i", *(*occurr + i));
    }

    printf("\n\n");
}

int main()
{
    int **pp;

    madeVector(pp);

    printf("\n--==[Outside Function]==--\n\n");
    for(int i = 0; i < 5; i++){
        printf(" %i", *(pp + i));
    }

    printf("\n\n");

    return 0;
}

I need to print all number in vector inside function "madeVector" and "main" using double pointer variables, how showed in code. But, it works only inside function "madeVector". I don't know how to print in "main" function. I tryed everthing, but it doesn't work.

Would someone help me to solve this problem?

Thanks in advance!

  • 1
    The problem: you don't allocate memory to store data anywhere. `vector` is local to the function. – Lundin Jun 01 '18 at 13:41
  • ... and so is `pOccurr`. – John Bollinger Jun 01 '18 at 13:42
  • Added 2 more canonical dupes to the list. The last one is probably the best for this case. – Lundin Jun 01 '18 at 13:44
  • It's almost working. – eddiesaliba Jun 01 '18 at 17:44
  • '#define TAM 5 void madeVector(int **occurr){ int *vector = malloc(sizeof(int) * TAM); int *pOccurr; for(int i = 0; i < TAM; i++) vector[i] = i + 1; pOccurr = vector; occurr = &pOccurr; printf("\n-[Inside Function]-\n\n"); for(int i = 0; i < TAM; i++){ printf(" %i", *(*occurr + i)); } printf("\n\n"); } int main() { int **pp; madeVector(pp); printf("\n-[Outside Function]-\n\n"); for(int i = 0; i < TAM; i++){ printf(" %i", (*pp + i)); } printf("\n\n"); return 0; } – eddiesaliba Jun 01 '18 at 17:57
  • But, vector inside function "madeVector" prints: **1 2 3 4 5** - perfect! However, inside function "main" it prints: **1 5 9 13 17** - And I don't know why it happens! – eddiesaliba Jun 01 '18 at 17:58
  • Until now I don't find a solution for my problem. If I find it, I'll write here. Thanks for your help! – eddiesaliba Jun 02 '18 at 19:04
  • I solved this problem! – eddiesaliba Jun 03 '18 at 14:45
  • #define TAM 5 void madeVector(int **occurr){ int *vector = malloc(sizeof(int) * TAM); int *pOccurr; for(int i = 0; i < TAM; i++) vector[i] = i + 1; pOccurr = vector; occurr = &pOccurr; printf("\nInside\n\n"); for(int i = 0; i < TAM; i++){ printf(" %d", *(*occurr + i)); } printf("\n\n"); } int main() { int *q; int **pp; q = &*pp; madeVector(pp); printf("\nOutside\n\n"); for(int i = 0; i < TAM; i++){ printf(" %d", (*q + i)); } printf("\n\n"); return 0; } – eddiesaliba Jun 03 '18 at 14:47

0 Answers0