I am making a program for a shopping list, the user passes the values of each product to the program and each one is stored in a vector. Then I add the elements of the vector to give the total value of the purchase, on that I created a function:
float valor(float *k, int *t){
int i;
float soma = 0;
for(i = 0; i<*t; i++){
soma += k[i];
}
return(soma);
}
And in main
, I call the program;
teste = valor(&vTotal, &quant);
printf("Valor total: %f", teste);
The argument vTotal
is the vector where the values of each product given by the user are and how much is the number of items in the vector.
The printf
is showing 0.00000 on the screen, already printei the value of the vector directly on the screen and is being correctly allocated in the vector, but I do not know why the sum is zeroing.
Complete example:
#include <stdio.h>
#include <stdlib.h>
#include "ghe.h"
int main()
{
float *vTotal;
int quant;
int i;
int teste = 0;
printf("Digite a quantidade: ");
scanf("%d", &quant);
vTotal = aloca(&quant);
for(i = 0; i<quant; i++){
printf("Digite o valor %d: ", i+1);
scanf("%f", &vTotal[i]);
}
teste = valor(&vTotal, &quant);
printf("\n %.2f", teste);
free(vTotal);
}
"ghe.h"
#include <stdio.h>
#include <stdlib.h>
float *aloca(int *num);
float valor(float *k, int *t);
float valor(float *k, int *t){
int i;
float soma = 0;
for(i = 0; i<*t; i++){
soma += k[i];
}
return(soma);
}
float *aloca(int *num){
float *u;
u = malloc(*(num)*sizeof(float));
return(u);
}