-1
I am very doubtful about the dynamic allocation and use of C pointers. I need to develop some exercises, but they are stuck because I am having some difficulty moving forward with the use of pointers and dynamic allocation. The following exercise calls for the following:
Make a program that reads a vector of real numbers of size chosen by the user and find out which is the largest and smallest value in the vector, together with its index.
I built it the way down. Could someone point out the error, please?
#include <stdio.h>
#include <stdlib.h>
float *alocaVetor(int n)
{
float *v;
v = (float *)malloc(n * sizeof(float));
return v;
}
void leVetor(float *v, int n)
{
int i;
for (i = 0; i < n; i++)
{
printf("Elemento %d: \n", i);
scanf("%f", &v[i]);
}
}
float *comparaVetor(float *v, int n)
{
float maior = v[0];
float menor = v[0];
for (int i = 0; i < n; ++i)
{
if (v[i] > maior)
maior = v[i];
if (v[i] < menor)
menor = v[i];
}
printf("%f", &maior);
printf("%f", &menor);
return v;
}
int main()
{
int n;
float *v;
float *resultado;
printf("\n Digite o numero de elementos do vetor: \n");
scanf("%d", &n);
v = alocaVetor(n);
printf("\n Digite: \n");
leVetor(v, n);
resultado = comparaVetor(v, n);
free(v);
return 0;
}
It is mandatory to use pointers in this exercise?
– Natan Fernandes
Give one studied in scope of variables. A variable declared in a function has the scope restricted to this function. In the case of
alocaVetor
is best to pass the float pointer as the function parameter.return v;
incomparaVetor
.– anonimo