Important Announcement
PubHTML5 Scheduled Server Maintenance on (GMT) Sunday, June 26th, 2:00 am - 8:00 am.
PubHTML5 site will be inoperative during the times indicated!

Home Explore RoboGarden C++

RoboGarden C++

Published by bassem.abdullah, 2016-02-22 13:02:32

Description: RoboGarden C++

Search

Read the Text Version

7.4.1 Relation between Arrays and PointersConsider and array:int arr[4];In arrays of C programming, name of the array always points to the first element of an ar-ray. Here, address of first element of an array is &arr[0]. Also, arr represents the address ofthe pointer where it is pointing. Hence, &arr[0] is equivalent to arr.Also, value inside the address &arr[0] and address arr are equal. Value in ad-dress &arr[0] isarr[0] and value in address arr is *arr. Hence, arr[0] is equivalent to *arr.7.5Passing pointers to functions in CC programming language allows you to pass a pointer to a function. To do so, simply declare thefunction argument as a pointer type. When, argument is passed using pointer, address of thememory location is passed instead of value.Example of Pointer And Functions #include <stdio.h> #include \"C:\API\ev3_command.h\" #include \"C:\API\ev3_lcd.h\" int getAverage(int *arr, int size); int main () { LcdInit(); int speed[5] = {100, 2, 3, 17, 50}; int average; average = getAverage( speed, 5 ) ; LcdText(1,5,5,\"The average number is : \"); writeInt(1,10,10,average) ; LcdExit(); } int getAverage(int *arr, int size) { int i, sum = 0; int avg; for (i = 0; i < size; i++) { sum += arr[i]; } avg = (double)sum / size; return avg; }SoftProduct Name of Class 2011 – mm/ddTraining Manual Page 45

Example #include <stdio.h> #include \"C:\API\ev3_command.h\" #include \"C:\API\ev3_lcd.h\" #include \"C:\API\ev3_output.h\" int strlen (const char *str) { int len = 0; while (*(str++)) ++len ; return len ; } int main () { char str []=\"roboVICS on \"; int strlenght; Lcdinit(); Lcdtext(1,10,10,\"Robovics ..........\"); wait(SEC)_1); int strlenght = strlen(str); robotMotionInit(); robotForwad(2*strlenght); wait(SEC_5); robotMotionExit(); }7.6Dynamic Memory AllocationThe exact size of array is unknown untill the compile time,i.e., time when a compier com-piles code written in a programming language into a executable form. The size of array youhave declared initially can be sometimes insufficient and sometimes more than required.Dynamic memory allocation allows a program to obtain more memory space, while runningor to release space when no space is required.Although, C language inherently does not has any technique to allocated memory dynami-cally, there are 4 library functions under \"stdlib.h\" for dynamic memory allocation.Function Use of Functionmalloc() Allocates requested size of bytes and returns a pointer first byte of allocated space Allocates space for an array elements, initializes to zero and then returns a pointer tocalloc() memoryfree() dellocate the previously allocated spacerealloc() Change the size of previously allocated space2011 – mm/dd SoftProduct Name of ClassPage 46 Training Manual

7.6.1 malloc()The name malloc stands for \"memory allocation\". The function malloc() reserves a block ofmemory of specified size and return a pointer of type void which can be casted into pointerof any form.7.6.1.1 Syntax of malloc() ptr=(cast-type*)malloc(byte-size)Here, ptr is pointer of cast-type. The malloc() function returns a pointer to an area ofmemory with size of byte size. If the space is insufficient, allocation fails and returns NULLpointer.ptr=(int*)malloc(100*sizeof(int));This statement will allocate either 200 or 400 according to size of int 2 or 4 bytes respec-tively and the pointer points to the address of first byte of memory.7.6.2 calloc()The name calloc stands for \"contiguous allocation\". The only difference between malloc()and calloc() is that, malloc() allocates single block of memory whereas calloc() allocatesmultiple blocks of memory each of same size and sets all bytes to zero.7.6.2.1 Syntax of calloc() ptr=(cast-type*)calloc(n,element-size);This statement will allocate contiguous space in memory for an array of n elements. For ex-ample:ptr=(float*)calloc(25,sizeof(float));This statement allocates contiguous space in memory for an array of 25 elements each ofsize of float, i.e, 4 bytes.7.6.3 free()Dynamically allocated memory with either calloc() or malloc() does not get return on itsown. The programmer must use free() explicitly to release space.7.6.3.1 syntax of free()free (ptr);This statement cause the space in memory pointer by ptr to be deallocated.Examples of calloc() and malloc()Write a C program to find sum of n elements entered by user. To perform this program,allocate memory dynamically using malloc() function.SoftProduct Name of Class 2011 – mm/ddTraining Manual Page 47

#include <stdio.h>#include <stdlib.h>int main(){ int n,i,*ptr,sum=0; printf(\"Enter number of elements: \"); scanf(\"%d\",&n); ptr=(int*)malloc(n*sizeof(int)); //memory allocated using malloc if(ptr==NULL) { printf(\"Error! memory not allocated.\"); exit(0); } printf(\"Enter elements of array: \"); for(i=0;i<n;++i) { scanf(\"%d\",ptr+i); sum+=*(ptr+i); } printf(\"Sum=%d\",sum); free(ptr);}Write a C program to find sum of n elements entered by user. To perform this program,allocate memory dynamically using calloc() function. #include <stdio.h> #include <stdlib.h> int main(){ int n,i,*ptr,sum=0; printf(\"Enter number of elements: \"); scanf(\"%d\",&n); ptr=(int*)calloc(n,sizeof(int)); if(ptr==NULL) { printf(\"Error! memory not allocated.\"); exit(0); } printf(\"Enter elements of array: \"); for(i=0;i<n;++i) { scanf(\"%d\",ptr+i); sum+=*(ptr+i); } printf(\"Sum=%d\",sum); free(ptr); return 0; }7.6.4 realloc()If the previously allocated memory is insufficient or more than sufficient. Then, you canchange memory size previously allocated using realloc().7.6.4.1 Syntax of realloc()ptr=realloc(ptr,newsize);ptr is reallocated with size of newsize.2011 – mm/dd SoftProduct Name of ClassPage 48 Training Manual

8 Structures And Unions8.1StructuresC arrays allow you to define type of variables that can hold several data items of the same kind butstructure is another user defined data type available in C programming, which allows you tocombine data items of different kinds.Structures are used to represent a record, Suppose you want to keep track of your books in alibrary. You might want to track the following attributes about each book: • Title • Author • Subject • Book ID8.1.1 Defining a StructureTo define a structure, you must use the struct statement. The struct statement defines a new datatype, with more than one member for your program. The format of the struct statement is this:struct [structure tag]{ member definition; member definition; ... member definition;} [one or more structure variables];The structure tag is optional and each member definition is a normal variable definition, such as inti; or float f; or any other valid variable definition. At the end of the structure's definition, before thefinal semicolon, you can specify one or more structure variables but it is optional. Here is the wayyou would declare the Book structure: struct robot { int motorsSpeed ; char * ownername; unsigned int batteryCharge ; float price; int hasWifi; }Ev3;8.1.2 Accessing Structure MembersTo access any member of a structure, we use the member access operator (.). The member accessoperator is coded as a period between the structure variable name and the structure member thatwe wish to access. You would use struct keyword to define variables of structure type. Following isthe example to explain usage of structure:SoftProduct Name of Class 2011 – mm/ddTraining Manual Page 49

#include <stdio.h> #include <string.h> struct robot { char name[50]; unsigned char speed; int direction; // 1 is forward -1 is backward . unsigned long time_ms ; // time with millisecond . }; int main( ) { struct robot robot1; struct robot robot2; /* robot 1 specification */ strcpy( robot1.name, \"volcano\"); robot1.speed = 100; roobot1.direction = 1; // robot1.time_ms = 2000; /* robot 2 specification */ strcpy( robot1.name, \"tornado\"); robot1.speed = 50; roobot1.direction = -1; // robot1.time_ms = 2000; /* print robot1 info */ if (robot1.direction==1) printf (\"Robot1 will move forward with speed = %d for %lu.\n\", robot1.speed,robot1.time_ms); else if (robot1.direction==-1) printf (\"%s will move backward with speed = %d for %lu.\n\", robot1.name,robot1.speed,robot1.time_ms); /* print robot2 info */ if (robot2.direction==1) printf (\"%s will move forward with speed = %d for %lu\".\n, robot2.name,robot2.speed,robot2.time_ms); else if (robot2.direction==-1) printf (\"%s will move backward with speed = %d for %lu\".\n, robot2.name,robot2.speed,robot2.time_ms); return 0; }8.1.3 Structures as Function ArgumentsYou can pass a structure as a function argument in very similar way as you pass any other variableor pointer. You would access structure variables in the similar way as you have accessed in theabove example:2011 – mm/dd SoftProduct Name of ClassPage 50 Training Manual

#include <stdio.h> #include <string.h> struct robot { char name[50]; unsigned char speed; int direction; // 1 is forward -1 is backward . unsigned long time_ms ; // time with millisecond . }; void printRobotInfo (struct robot rob){ if (rob.direction==1) printf (\"%s will move forward with speed = %d for %lu .\n\",rob.name ,rob.speed,rob.time_ms); else if (rob.direction==-1) printf (\"%s will move backward with speed = %d for %lu .\n\",rob.name ,rob.speed,rob.time_ms); } int main( ) { struct robot robot1; struct robot robot2; /* robot 1 specification */ strcpy( robot1.name, \"volcano\"); robot1.speed = 100; roobot1.direction = 1; // robot1.time_ms = 2000; /* robot 2 specification */ strcpy( robot1.name, \"tornado\"); robot1.speed = 50; roobot1.direction = -1; // robot1.time_ms = 2000; /* print robot1 info */ printRobotInfo(robot1); /* print robot2 info */ PrintRobotInfo(robot2); return 0; }Using our APIs translate the previous example to a real robot example that could run on the robotUse the following guidline ,Substitute the function named printRobotInfo(struct robot rob ); to makerobotMove(struct robotrob) ;SoftProduct Name of Class 2011 – mm/ddTraining Manual Page 51












Like this book? You can publish your book online for free in a few minutes!
Create your own flipbook