Rob Toulson / Mbed 2 deprecated PE_10-05_PointersExample

Dependencies:   mbed

Embed: (wiki syntax)

« Back to documentation index

Show/hide line numbers main.cpp Source File

main.cpp

00001 /* Program Example 10.5: Pointers example for an array average function
00002                                                                      */
00003 #include "mbed.h"
00004 Serial pc(USBTX, USBRX);                               // setup serial comms
00005 char data[]={5,7,5,8,9,1,7,8,2,5,1,4,6,2,1,4,3,8,7,9}; //define some input data
00006 char *dataptr;                           // define a pointer for the input data
00007 float average;                           // floating point average variable
00008 
00009 float CalculateAverage(char *ptr, char size);     // function prototype
00010 
00011 int main() {    
00012   dataptr=&data[0];       // point pointer to address of the first array element
00013   average = CalculateAverage(dataptr, sizeof(data));      // call function
00014   pc.printf("\n\rdata = ");
00015   for (char i=0; i<sizeof(data); i++) {           // loop for each data value
00016     pc.printf("%d ",data[i]);                     // display all the data values
00017   }
00018   pc.printf("\n\raverage = %.3f",average);        // display average value
00019 }
00020 
00021      // CalculateAverage function definition and code 
00022 float CalculateAverage(char *ptr, char size) {
00023   int sum=0;                // define variable for calculating the sum of the data
00024   float mean;               // define variable for floating point mean value
00025   for (char i=0; i<size; i++) {
00026     sum=sum + *(ptr+i);            // add all data elements together
00027   }
00028   mean=(float)sum/size;            // divide by size and cast to floating point
00029   return mean;             
00030 }