Added book examples

This commit is contained in:
Louise Brown
2022-04-08 16:12:38 +01:00
parent 5b205092a7
commit 1c0a9e7b6a
59 changed files with 1381 additions and 0 deletions

View File

@@ -0,0 +1,40 @@
#include <stdio.h>
#include <stdlib.h>
// Simple function to populate an integer array
void PopulateTheArray ( int Size, int ArrayData[])
{
int i; // Variable to use in our loop
for ( i = 0 ; i < Size ; i++)
{
ArrayData[i] = 2*i + 1; // Treat it like a normal array
}
}
// Simple function do display contents an integer array
void DisplayTheArray ( int Size, int ArrayData[])
{
int i; // Variable to use in our loop
for ( i = 0 ; i < Size ; i++)
{
printf ("Item %d of the array contains %d\n", i, ArrayData[i]);
}
}
// Main () - execution starts here
int main (void)
{
int Data[10];
// Pass the size of the array and the array to our function -
// remembering that the array name on its own is the base address,
// and so is the same as passing &Data[0]
PopulateTheArray(10, Data);
DisplayTheArray(10, Data);
return (0); // Exit indicating sucess
}

View File

@@ -0,0 +1,55 @@
#include <stdio.h>
#include <stdlib.h>
// Simple function to populate an integer array
void PopulateTheArray ( int Size, int ArrayData[])
{
int i; // Variable to use in our loop
for ( i = 0 ; i < Size ; i++)
{
ArrayData[i] = 2*i + 1; // Treat it like a normal array
}
}
// Simple function do display contents an integer array
void DisplayTheArray ( int Size, int ArrayData[])
{
int i; // Variable to use in our loop
for ( i = 0 ; i < Size ; i++)
{
printf ("Item %d of the array contains %d\n", i, ArrayData[i]);
}
}
// Main () - execution starts here
int main (void)
{
int iSizeForArray;
int *pData; // A pointer to hold the base address of out array
// Ask for the size of the array and store result
printf("\nPlease enter the size of the array to dynamically allocate");
scanf ("%d", &iSizeForArray);
// Use calloc with checking
pData = calloc ( iSizeForArray, sizeof (int));
// Check we got the memory
if ( pData == NULL)
{
printf ("\nSorry, I could not allocate the memory, bye!");
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);
free (pData); // Free up the memory before exiting
return (0); // Exit indicating sucess
}