How could I read let\'s say 10 floats and store them in an array without wasting any memory?
Aha. It's not reading the floats that's the problem, it's the memory. You read in i, and you need an array that holds exactly i floats.
This really does smell like homework, which is fine, but I'm too much the teacher to give you the full answer. So I'll tell you, what you need is a C function named malloc() and a C operator (it looks like a function but it's actually built into the language) named sizeof.
Have a look at this tutorial.
Yup, you got it there. Here's 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
I'd do it with two changes:
malloc
for anything besides characters*(pValues+index)
is exactly equivalent to pValues[index]
. So I'd rewrite this as:
int n,index;
float temp;
scanf("%d",&n);
float *pValues=(float *)malloc(n*sizeof(float));
for(index=0;index
Let's look at one more transformation of the code. You have pValues
, which is a pointer to float
. You have &temp
, which is also a pointer to float
, because &
is the address-of operator and temp
is a float
. AND, you're just doing pointer arithmetic with your index. So, we could rewrite this one more time as:
int n,index; // Don't need temp
scanf("%d",&n);
float *pValues=(float *)malloc(n*sizeof(float));
for(index=0;index
Now, quiz question: what would happen if you made the loop
for(index=0;index