Doubt to return arrays on pointers. below is the code I tried, but only returns addresses

Asked

Viewed 57 times

0

Good night, you guys. following, I would like a help to return a vector, whose goal is to implement a function that takes an integer vector V and returns another integer vector dynamically allocated with all values of V that are between the minimum and maximum value (which are also passed as a parameter to the function). Anyone who can help me, I’d appreciate it.

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

int * valores_entre(int * v, int n, int max, int min){
  int i;
  int cont = 0;
  int *p;
  for (i = 0; i < n; i++){
    if (v[i] > min && v[i] < max){
      cont++;
      p = (int )malloc(contsizeof(int));
      p[i] = v[i];
    }
  }
  free(p);
  return p;
}

int main (void){
  int vet[] = {1, 2 ,3 ,4 ,5};
  int tam = sizeof(vet)/sizeof(int);
  int * resultado = valores_entre(vet, 5, 1, 5);
  int i;
  for (i =0; i < 5; i++){
    printf("%d\n", resultado[i]);
  }
  return 0;
}
  • Your code has some easy-to-understand errors like the undeclared 'contsizeof()' function or the fact that you release the p pointer before returning the function, or the memory leak within the loop. This is all easy to solve, what is not easy to solve is the logic of the between-valued function. I explain, it returns an array of integers, the problem is that only the array is useless and dangerous, because you need to know the size of the array to not happen what happens in the last of the main function which is the program reading memory out of the size of the array.

  • The vector used in the input will always be an ordered vector ?

1 answer

0

Assuming that the input vector will always be ordered and with a " 0" indicating the end of the vector:

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

int* valores_entre(int* v, int min, int max)
{
  /* Encontra o tamanho do vetor (presumindo que ele termina em 0) */
  int tam = 0;
  for (int i=0; v[i]!=0; i++) {
    tam++;
  }

  /* Aloca memória para um vetor de inteiros */
  int* resultado = malloc((tam - 1) * sizeof(int));
  int* vetor = resultado;

  /* Compara e adiciona número ao vetor */
  for (int j=0; j<=tam; j++) {
    if ((v[j] > min) && (v[j] < max)) {
        *vetor = v[j];
        vetor++;
    }
  }
  *vetor = 0; /* Adiciona terminador zero */

  return resultado;
}

int main (void) {
  int vet[] = {1, 2, 3, 4, 5, 0};
  int* resultado = valores_entre(vet, 1, 5);
  int i = 0;
  while (resultado[i] != 0) {
    printf("%d\n", resultado[i]);
    i++;
  }
  return 0;
}

Browser other questions tagged

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