Your overall goal is to write a C code that allocates memory
Your overall goal is to write a C code that allocates memory for a floating array, \"computes\" values in the array, then saves those values to a file. The code comprises the following steps Start with two macro definitions (#define): an integer which defines how big your floating array will be (how much memory you\'ll allocate), and a string that is the filename to which you\'ll save data. Define three variables (minimally): a file pointer, a float pointer, and an integer Allocate memory (use sizeof(float) to know how large, and use the integer you defined in the first bullet above to allocate that many of them) for the float pointer. Start a for loop that \"computes\" and sets values for the float pointer (i e that fills the array with values) Make the values merely the loop index plus 1/2 Thai is, on the loop where i = 0. set the pointer to 0 + 1/2 On the next loop, i = 1 and set the next value in the pointer to 1 + 1/2 You may access the floating array (i e the pointer) by any way you wish - by incrementing the pointer, or using brackets to index it. Open the file you named in the string in the first bullet above. Write every other value of the file pointer to the tile, using formatted printing Use a statement like \"Value at index () is ()\". where the first set of parenthesis should contain the loop index and the second set the floating point value. Close the file. For at least two functions (allocating memory, opening a file, closing a file), use the returned value to check if the function competed successfully, and use flow control to exit the program \"gracefully\" (i e print out something and return(-1) or similar) if it failed. Run the code for two values at your integer size (the value defined in the first bullet) 30 and 60.
Solution
#include <stdio.h>
#include <stdlib.h>
#define SIZE 30 //macros
#define FILENAME \"file.txt\"
int main()
{
FILE *fp; //file pointer
float *ptr; //float pointer
int i; //int
ptr = (float*)malloc(SIZE*sizeof(float)); //dynamic memory allocation
for(i=0;i<SIZE;i++)
{
*(ptr +i) = i+1/2;
// printf(\"\ %f\",*(ptr+i));
}
fp =fopen(FILENAME,\"w\"); //open file in write mode
if (fp == NULL) //if file not opened ,output error
{
printf(\"Error opening file!\ \");
exit(1);
}
for (i=0; i<SIZE; i++)
fprintf(fp,\"Value at index %d is %f\ \", i,*(ptr+i)); //writing to file
fclose(fp); //close file
free(ptr); //free memory allocated to pointer variable
return 0;
}
