89 lines
2.2 KiB
C
89 lines
2.2 KiB
C
#include <stdio.h>
|
|
#include <math.h>
|
|
#include <stdlib.h>
|
|
|
|
|
|
float degrees_to_radians(float degrees) {
|
|
return M_PI * degrees / 180.0;
|
|
}
|
|
|
|
|
|
// Simple function to populate an integer array
|
|
void PopulateTheArray ( int Size, float ArrayData[])
|
|
{
|
|
int i; // Variable to use in our loop
|
|
|
|
for ( i = 0 ; i < Size ; i++)
|
|
{
|
|
ArrayData[i] = degrees_to_radians(i); // Treat it like a normal array
|
|
}
|
|
}
|
|
// Simple function do display contents an integer array
|
|
void DisplayTheArray ( int Size, float ArrayData[])
|
|
{
|
|
int i; // Variable to use in our loop
|
|
|
|
for ( i = 0 ; i < Size ; i++)
|
|
{
|
|
printf ("%d\t%0.3f\n", i, ArrayData[i]);
|
|
}
|
|
}
|
|
|
|
int SaveArrayBinary (char *filename, int Size, float ArrayData[])
|
|
{
|
|
FILE *fp; // File Pointer
|
|
int i; // Variable to use in our loop
|
|
|
|
fp = fopen(filename, "wb");
|
|
// if file open failed, return error to caller
|
|
if (fp == NULL) {
|
|
return 1;
|
|
}
|
|
|
|
// write data
|
|
fwrite(ArrayData, sizeof(float), Size, fp);
|
|
// close file, returns 0 on successful closing (therefore function has executed sucessfully)
|
|
return fclose(fp);
|
|
}
|
|
// Main () - execution starts here
|
|
int main (void)
|
|
{
|
|
char filename[2049];
|
|
int rc, iSizeForArray;
|
|
float *pData; // A pointer to hold the base address of out array
|
|
|
|
// Ask for the size of the array and store result
|
|
|
|
printf("Please enter the size of the array to dynamically allocate: ");
|
|
scanf ("%d", &iSizeForArray);
|
|
|
|
// Use calloc with checking
|
|
pData = calloc( iSizeForArray, sizeof (float));
|
|
|
|
// Check we got the memory
|
|
if ( pData == NULL)
|
|
{
|
|
printf ("Sorry, I could not allocate the memory, bye!\n");
|
|
return -1;
|
|
}
|
|
|
|
// Pass the size, iSizeForArray) and the pointer created
|
|
// which points to the start of the sucesfully allocated memory
|
|
|
|
PopulateTheArray(iSizeForArray, pData);
|
|
DisplayTheArray(iSizeForArray, pData);
|
|
|
|
// Exercise doesn't ask to use function but kind of pointless without
|
|
printf("Enter filename: ");
|
|
scanf("%2048s", filename);
|
|
rc = SaveArrayBinary(filename, iSizeForArray, pData);
|
|
if (rc != 0) {
|
|
printf("Error saving file\n");
|
|
free(pData);
|
|
return rc;
|
|
}
|
|
|
|
free(pData); // Free up the memory before exiting
|
|
return (0); // Exit indicating sucess
|
|
}
|