The solution is simpler than it seems. From what I understand the use of the pointer is inadequate in this code. Using the vector is enough to solve the problem.
#include <stdio.h>
int main() {
float vet[10];
for (int i = 0; i < 10; i++) {
printf("\nDigite um valor: ");
scanf("%f", &vet[i]); //preciso passar o endereço do elemento do vetor
printf("%f", vet[i]);
}
}
Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.
I took the opportunity to improve some things and leave the code more modern and within the standard.
It is possible to change this code to use pointers.
#include <stdio.h>
#include <stdlib.h>
int main() {
float *vet = malloc(sizeof(float) * 10);
for (int i = 0; i < 10; i++) {
printf("\nDigite um valor: ");
scanf("%f", &vet[i]);
printf("%f", vet[i]);
}
}
Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.
There you do not need the vector. Note that pointers and vectors are concepts that can be reasonably interchangeable in certain circumstances in C. Reading the question linked here is to understand why even having allocated with pointer, I could use the vector index syntax, which is just syntax sugar for a pointer access calculation. You could do the calculation by hand to use pointer syntax, but it’s unnecessary.
The difference is that the first code allocates memory in the stack, and this with pointer allocates in heap.
You need to allocate the memory for each pointer. You created 10 pointers, you need to allocate them all... I’m running out of time to respond now. Soon someone will come to answer, ;)
– Franchesco
vet
is an array of 10 pointers. To make an array of 10 numbers usesfloat vet[10];
and the address of each element in the scanf:if (scanf("%f", &vet[i]) != 1) /* erro */;
.– pmg
@Earendul When I declare float *vet[10] I’m no longer doing this? If not, I need to use malloc for what exactly?
– Daniela Morais
This, as you said, you just stated. But you still need to allocate memory.
– Franchesco
@Danielamorais do you just want to read 10 numbers and print them? Is there any extra requirement? Is there a reason to have used the pointer?
– Maniero
@bigown Yes, my problem is "Create an array with n elements, and each vector position will correspond to a pointer to a float value. Read n values and store them in memory."
– Daniela Morais