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.
– user142154
The vector used in the input will always be an ordered vector ?
– Clayton A. Alves