4
I am making a program for a shopping list, the user passes to the program the values of each product and each one is stored in a vector. Then we added the elements of the vector to give the total value of the purchase, so 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 the main
, I’ll call the program;
teste = valor(&vTotal, &quant);
printf("Valor total: %f", teste);
The argument vTotal
is the vector where are the values of each product given by the user and Quant is the amount of vector items.
The printf
is shows 0.00000 on the screen, now printi the value of the vector directly on the screen and being correctly allocated in the vector, but I don’t know why the sum is zeroing.
Full 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);
}
Man, thank you so much. I’m starting now with dynamic allocation and I’m still kind of lost with pointers, thanks anyway. Just a question. For functions that I declare one of the arguments as a pointer, it is not necessary to use &? After this your answer, I realized that when I do the value(&Vtotal, &Quant), gives zero, but when I take &, the function returns the correct value
– Mateus Lucas
When the parameter expects a pointer and the argument passed is already a pointer it cannot use the operator
&
to pass. The second I took off because it doesn’t need to be a pointer to anything.– Maniero