[Solved] I need help solving this code in C, please


This sounds like it is homework. What does your text book can course material say? If you come here for just the answers without the understanding, then you may pass the assignment, but you won’t learn from the course.

Assuming that you will use this information to learn, here is some information to get you started.

a.) Create a float array using memory allocation to store the GPA scores of 10 students. Assign values to it (your choice)

To do this, you need to use malloc. Your code currently uses the stack by declaring it as a constant size array. Instead, you should be doing something like this:

float* studentGPA = (float*)malloc(10 * sizeof(float));

Then initialize it with values. They way you are doing that is fine.

b.) Find the maximum GPA in this array.

I don’t know why you are using strange pointer arithmetic, but finding the maximum value in an array is easy. Simply loop over the range of the array and compare to a previously known value. For example.

float maxVal = studentGPA[0];
for (int i=1; i<10; i++) 
  if (studengGPA[i] > maxVal) 
    maxVal = studentGPA[i];

c.) Write the contents of this array to a file alloc.txt

There are lots of ways to do this. One could write the contents directly using write, or print them to a file using fprintf. The former is more exact, but the latter actually makes a human readable file. For example, if you write the integer 16 to a file, you will actually write 4 bytes (the usual size of an integer) and the values (in hex) will be 0x10 0x00 0x00 0x00. However, if you print the number, you’d write the characters ‘1’ and ‘6’. These map to ascii values of 0x31 and 0x36. In this example, printing makes a smaller file, but in general, it is the other way around. An integer can express very large numbers, and printing will take one byte per digit. However, writing will always take 4 bytes.

That said, here is a quick way to print to a file.

FILE* outfile=fopen("alloc.txt", "w");
for (i=0; i<10; i++) 
  fprintf(outfile, "%f\n", studentGPA[i]);

d.) Expand the array to accommodate the GPA scores of 5 more students.

You could do this manually by allocating a new array of size 15, and then copying the old array to it. However, realloc is probably what you are looking for.

realloc((void*)studentGPA, 15 * sizeof(float));

e.) Write the contents of this expanded array to another file realloc.txt

See above.

f.) Read the contents of realloc.txt to another float array named Expand.

Similar to fprintf, you can use fscanf. It will read formatted input into your values.

float* expand = (float*)malloc(15 * sizeof(float));
FILE* infile=fopen("realloc.txt", "r");
for (i=0; i<15; i++)
  fscanf(infile, "%f", &(expand[i]));

g.) Print out the contents of Expand array.

Simply use printf to print to the screen.

for (i=0; i<15; i++)
  printf("%f\n", expand[i]);

1

solved I need help solving this code in C, please