how can a user of a program store info in arrays such as a float number and can be calculated for an average later in the program? im trying to make a program to calculate someones grade point average.
Asked
Active
Viewed 4,619 times
2 Answers
0
int maxGrades = 50; // pick this
int numGrades = 0;
float[] grades = malloc (sizeof (float) * maxGrades);
// in a loop somewhere
if(numGrades == maxGrades) {
maxGrades *= 2;
float[] newGrades = malloc (sizeof (float) * maxGrades);
for(int i = 0; i < numGrades; i++) newGrades[i] = grades[i];
grades = newGrades;
}
grades[numGrades++] = theNewestGrade;

corsiKa
- 81,495
- 25
- 153
- 204
-
1Remember to free that memory (this program will probably end after this but it is good practice). – Argote Feb 16 '11 at 02:38
-
Please provide code that compiles. And what's your question? Your code stores floats in arrays (although mostly it stores undefined values from grades into newgrades -- better done by memcpy) so you apparently know how to do that. – Jim Balter Feb 16 '11 at 06:28
-
Hey I'll be straight up, I'm a Java guy. I was just illustrating the basic principles I would use to store the data in an array. Users of sufficient reputation are welcome to edit to remove inconsistencies. – corsiKa Feb 16 '11 at 16:01
0
Transitting from java to C, the biggest "concept jump" you have to make is Pointers.
Try allocating your floats this way:
float *float_array = malloc(amount_of_elemts_in_array * sizeof(float))
You can then iterate through using
float_array[index]
Having this pointer will enable you to pass float_array
in and out of functions by reference which is a great convenience since you don't want to recreate instances over every function call.
Pass float_array
into functions using:
Function Declaration: void function_that_uses_float_array(float *placeholder);
Function Call: function_that_uses_float_array(placeholder);
Pass float_array
out of functions using:
Return statement: return a_float_pointer;
One level up the stack: float_array = function_that_returns_a_float_pointer();
Arrays are automatically passed by reference.
Hope this helps point you in the right direction.

Igbanam
- 5,904
- 5
- 44
- 68
-
sorry, I was reading the other answer with Java, that's why I thought the person who asked the question was transitting from Java. Disregard the first line if you're not coming from Java :) – Igbanam Mar 26 '11 at 23:44