How to use a function to fill all positions of the dynamically allocated vector?

Asked

Viewed 163 times

-1

Good afternoon guys, I’m seeing for the first time the C language and I’m not making progress on a job.

First you are asked to create a function int receive Operator() This function will request the typing of an integer and positive number, validate it, so that it is not typed incorrectly, and, after validation, return the number to who requested it. I did it this way:

  int receberInteiro() {

int num;

 setbuf(stdout,NULL);

   do 
   {

      printf("Informe um numero inteiro (Não é aceito numero negativo):");
      scanf("%d", &num);


   }while (num < 0);

 return num;
}

You are then asked to create a second function by filling it with Cvetor(int *vector, int size);

This function will fill all positions of the dynamically allocated vector - use function 01 for this fill. At the end return the sum of the elements.

At that moment I am stuck, because I do not know how to use what the user typed in the first function to fill all positions of the dynamically allocated vector.

This is because the third function would be void alocarVetor(int *somaTotal)

and it would request the size of the vector from the user (call function 01 to fill this item) then declare an integer pointer, which will receive the allocation, then allocate the vector, of the size indicated by the user, as item a, into the pointer of item b. And finally execute function 02 to fill the positions of the allocated vector. The value returned by function 02 will be sent, via parameter by reference, to those who requested function 03.

Since I got stuck in the 2 I don’t know where to start in the 3.

1 answer

0

The second function is:

int preencherVetor(int *vetor, int tamanho) {
    int i, soma=0;
    vetor = (int *) malloc(tamanho * sizeof(int));
    for (i=0; i<tamanho; i++) {
        vetor[i] = receberInteiro();
        soma += vetor[i];
    }
    return soma;
}

Browser other questions tagged

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