How could I read let's say 10 floats and store them in an array without wasting any memory?
相关问题
- Multiple sockets for clients to connect to
- What is the best way to do a search in a large fil
- glDrawElements only draws half a quad
- Index of single bit in long integer (in C) [duplic
- Equivalent of std::pair in C
As simple as it could be :)
You'll have to be more specific about the problem.
Unless you have something else that you need to do with these numbers, then the easiest way to save memory is not to store them in an array to begin with.
It sounds like what you want is something like.
sum = 0;
do
read current
sum += current
while (you haven't yet read 10 numbers);
The answer to your question is that you cannot add things to an array and expect the array to use 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.
I'd do it with two changes:
malloc
for anything besides characters*(pValues+index)
is exactly equivalent topValues[index]
.So I'd rewrite this as:
Let's look at one more transformation of the code. You have
pValues
, which is a pointer tofloat
. You have&temp
, which is also a pointer tofloat
, because&
is the address-of operator andtemp
is afloat
. AND, you're just doing pointer arithmetic with your index. So, we could rewrite this one more time as:Now, quiz question: what would happen if you made the loop
I know, it's like the above, but doesn't use the extra int in case it's not optimized out. hehe
To use even less memory us the code below. They're all read into an array, but only the last one to be read in is in the array:
sounds like homework.
read the number of floats from the input. multiply that by the size of an individual float allocate that exact number of bytes storing the address in a pointer to floats have a loop read in the floats from the input have a loop that adds up all the floats in the array
My guess here is the homework lesson is to realize the connection between the term pointer and array, although you can do this without any array indexing, but your question implies that you have to use an array.