Doubt regarding C pointers

Asked

Viewed 20 times

1

I am writing a program that has 3 files: algorithms. h, algorithms. c and main. c.

This program has several integer vector ordering algorithms. With the intention of making the program more flexible, the size of the automatically generated vector is defined by the user: (below code is in the main)

    case 5:
        printf("\nDigite quantos numeros deseja alocar.\n");
        scanf("%d", &tamanho);
        printf("\nDigite a faixa de geracao. EX: 0 ate 100, digite 100.\n");
        int faixa;
        scanf("%d", &faixa);
        tamanho = randomvetor(vetor, tamanho, faixa);
        break;

And here is the function Random vector:(code below is in algorithms. c)

int randomvetor(int* vetor, int tamanho, int faixa){
int aleatorio;
vetor = (int*)malloc(sizeof(int) * tamanho);
for (int i = 0; i < tamanho; i++) {
    aleatorio = rand() % faixa;
    vetor[i] = aleatorio;
}
imprimirtudo(vetor, tamanho);
return tamanho;}

It generates the random vector and prints. The problem, is that when returning to main, for some reason I do not know the pointer to the vector is lost and the program starts to consider vetor = null again.

Someone knows the solution?

OBS: with size vector and fixed values the algorithms work normally.

  • In C every parameter pass is by value. Note that in the function the pointer to integer vector is in the parameter stack to which the address of the allocated area is assigned, it is not the address of the vector existing in main.

No answers

Browser other questions tagged

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