Reading floats into an array
Yeah. It's not reading floats, that's the problem, it's memory. You are reading into i and you want an array that has exactly i floats.
It really smells like homework, which is good, but I'm too much of a teacher to give you a complete answer. So I'll tell you that you need a C function called malloc () and a C operator (it's like a function, but actually built into the language) called sizeof.
Check out this tutorial .
Yes, you are there. Here is the code from your comment, formatted.
int n,index;
float temp;
scanf("%d",&n);
float *pValues=(float *)calloc(n,sizeof(float));
for(index=0;index<n;index++) {
scanf("%f",&temp);
*(pValues+index)=temp;
}
I would do it with two changes:
- More idiomatic to use
malloc
for anything other than symbols - In C, arrays and pointers are very closely related; is actually
*(pValues+index)
exactly equivalentpValues[index]
.
So, I would rewrite this as:
int n,index;
float temp;
scanf("%d",&n);
float *pValues=(float *)malloc(n*sizeof(float));
for(index=0;index<n;index++) {
scanf("%f",&temp);
pValues[index]=temp;
}
Let's take a look at another code transformation. You have pValues
which is a pointer to float
. You have &temp
, which is also a pointer to float
because it &
is an operator-address, and temp
is float
. And, you're just doing index-index arithmetic. So, we could rewrite this again as:
int n,index; // Don't need temp
scanf("%d",&n);
float *pValues=(float *)malloc(n*sizeof(float));
for(index=0;index<n;index++) {
scanf("%f",pValues+index);
}
Now a quiz question: what happens if you did a loop
for(index=0;index<n;index++) {
scanf("%f",pValues++);
}
a source to share
You should be more specific about this problem.
If you have anything else you need to do with these numbers, then the easiest way to save memory is to not store them in an array to start with.
It sounds like you want something like.
sum = 0;
make
read current
sum + = current
while (you haven't read 10 numbers yet);
a source to share
float arr[10];
for(i = 0; i < 10; i++){
scanf("%f", &arr[i]);
}
I know it is as above, but does not use an extra int in case it is not optimized. hehe
To use even less memory use the code below. They are all read into an array, but only the last one to be read is in the array:
float arr[1];
for(i = 0; i < 10; i++){
scanf("%f", &arr[0]);
}
a source to share
sounds like homework.
read the number of floats from the entrance. multiply by the size of the individual float allocate the exact number of bytes storing the address in the pointer to floats have a loop readable in the floats from the input there is a loop that sums all the floats in the array
My guess is that the lesson lesson is to implement the link between the pointer and the term array, although you can do this without indexing the array, but your question implies that you need to use an array.
a source to share