Function to sum elements of a vector does not return correct value

3

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);
}
    
asked by anonymous 20.08.2016 / 19:52

1 answer

2

The code had several problems, even to compile I had to deal with a lot. I ended up getting the final result that worked. I can not say what the problem was in the question, in theory I did not change any logic, I only fixed what prevented the compilation. There is a chance of a comflifo with the aloca() function that exists in C. I did in a way that I consider to be simpler and organized trying to keep the intention.

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

float valor(float *k, int t){
    float soma = 0;
    for (int i = 0; i < t; i++){
        soma += k[i];
    }
    return soma;
}

int main() {
    int quant;
    printf("Digite a quantidade: ");
    scanf("%d", &quant);
    float *vTotal = malloc(quant * sizeof(float));
    for(int i = 0; i < quant; i++){
        printf("Digite o valor %d: ", i + 1);
        scanf("%f", &vTotal[i]);
    }
    float teste = valor(vTotal, quant);
    printf("\n %.2f", teste);
    free(vTotal);
}

See running on ideone .

    
20.08.2016 / 20:39