SlideShare a Scribd company logo
Advanced+pointers
Declaration: returnType (*varName)(parameterTypes); Examples: int (*f)(int, float); int *(*g[])(int, float); int *(*g[])(int, float); pointer to a function that takes an integer argument and a float argument and returns an integer pointer to a function that takes an integer argument and a float argument and returns a  pointer  to an integer An  array  of pointers to functions – Each function takes an integer argument and a float argument and returns a pointer to an integer
Function Pointers are pointers, i.e. variables, which point to the address of a function. A function pointer always points to a function with a specific signature! Thus all functions, you want to use with the same function pointer, must have the  same parameters and return-type! Example: Task to perform one of the four basic arithmetic operation Solution:  i)The task is first solved using a switch- statement.  ii)Then it is shown, how the same can be done  using a function pointer CS 3090: Safety Critical Programming in C
Void Pointers CS 3090: Safety Critical Programming in C
  void  pointer seems to be of limited when combined with the ability to cast such a pointer to another type, they turn out to be  quite useful and flexible . CS 3090: Safety Critical Programming in C
int * const ptr2  indicates that  ptr2 is a pointer which is constant. This means that ptr2 cannot be made to point to another integer. However the integer pointed by ptr2 can be changed. For eg. int x=10,  y=20;  int * const ptr=&x;  *ptr=30; ptr=&y; //illegal Where as a  Pointer to constant  is  const int * ptr1  indicates that ptr1 is a pointer that points to a constant integer. The integer is constant and cannot be changed. However, the pointer ptr1 can be made to point to some other integer. For eg.  int x=10; y=20; const int *ptr=&x;  x=20; ptr=&y; *ptr=30;  //Illegal
1. Near pointer 2. Far pointer 3. Huge pointer CS 3090: Safety Critical Programming in C
Entire RAM has divided in numbers of equal parts, which are known as memory cells. Following diagram represents the 256 MB RAM. Each cell can store one-byte data. Data are stored in the  binary number system. That is a character data reserves one memory cell while floating data reserves four memory cells. Each memory cell has unique address. Address is always in whole number and must be in increasing order.  CS 3090: Safety Critical Programming in C
Advanced+pointers
int a = 4; Q. If you know memory address of first cell is 0x5000 then  what would be the memory address of next memory cell? A. It will 5001 since integer data always stores at  continuous memory location and as we know memory address always in increasing order. CS 3090: Safety Critical Programming in C
RAM has divided into two parts: (1)        Extended memory (useless) (2)        Residence memory   When any program is executed it is stored in the residence memory. All the c variables are stored in the residence memory. Depending upon the compiler the residence memory is defined. For example. In Turbo C 3.0 its 1MB. In turbo C 3.0, 20 bits address of the memory cell is known as physical address or real address. In 20 bits, we can represent address   from 0x00000 to 0xFFFFF. That is all c variables must have memory address within this range.
CS 3090: Safety Critical Programming in C
A C programmer cannot not decides what will be the memory address of any variables.
Residential memory of RAM of size 1MB has divided into 16 equal parts. These parts is called segment. Each segment has size is 64 KB. 16 * 64 KB = 1 MB CS 3090: Safety Critical Programming in C
Advanced+pointers
Note: In turbo c 3.0 physical addresses of any variables are stored in the 20 bits. But we have not any pointers  of size 20 bits. So pointers cannot access whole residence  memory address. To solve this problem we there are three types pointers in c language.  They are 1. Near pointer 2. Far pointer 3. Huge pointer CS 3090: Safety Critical Programming in C
Each segment has divided into two parts. 1. Segment no (4 bit) 2. Offset address (16 bit) CS 3090: Safety Critical Programming in C
#include<stdio.h> int main(){ int x; printf(&quot;%u &quot;,&x); //To print offset address printf(&quot;%p &quot;,x); //To print segment address printf(&quot;%p &quot;,&x); //To print offset address printf(&quot;%fp &quot;,&x); //To print segment address : offset address return 0;} CS 3090: Safety Critical Programming in C
All the segments are used for specific purpose. Like segment number 15 is used for ROM, segment number 14 is used for BIOS etc. CS 3090: Safety Critical Programming in C
CS 3090: Safety Critical Programming in C
Segment number eight  has special name which is known as data segment. This segment has been divided into four parts. This is very important for c programming CS 3090: Safety Critical Programming in C
1. Stack area:- All automatic variables are created into stack area.Default storage class of any local variable is auto.This variable may be int, char, float, array, pointer, struct, union etc.It also return function argument and return address.It follow LIFO data structure. It has two part one for initialize variable another for non-initialize variable.All initialize variable are more nearer than uninitialized variable and vice versa. 2. Data area : All static and extern variable are created in the data area. CS 3090: Safety Critical Programming in C
3. Heap area: Malloc and calloc always allocate memory in the heap area.It is used for dynamic memory allocation.It’s size depends upon free space in the memory. 4. Code area : Function pointer can only access code area.Size of this area is always fixed and it is read only area CS 3090: Safety Critical Programming in C
The pointer which can points only 64KB data segment or segment number 8 is known as near pointer. CS 3090: Safety Critical Programming in C
The limitation is that you can only access 64kb of data at a time, because that is the size of a segment - 64kb
The pointer which can point or access whole the residence memory of RAM i.e. which can access all 16 segments is known as far pointer. CS 3090: Safety Critical Programming in C Far Pointer
09/27/11 CS 3090: Safety Critical Programming in C
Size of far Pointer is 4 byte or 32 bit #include<stdio.h> int main(){ int x=10; int far *ptr; ptr=&x; printf(&quot;%d&quot;,sizeof ptr); return 0;} Output: 4 CS 3090: Safety Critical Programming in C
CS 3090: Safety Critical Programming in C Same as the far Pointer They are normalized.
Size of far Pointer is 4 byte or 32 bit #include<stdio.h> int main(){ int x=10; int far *ptr; ptr=&x; printf(&quot;%d&quot;,sizeof ptr); return 0;} Output: 4 CS 3090: Safety Critical Programming in C
int main(int argc, char *argv[]) { ... }  When main is called, argc will be a count of the number of command-line arguments, and argv will be an array of the arguments themselves. Since each word is a string which is represented as a pointer-to-char, argv is an array-of-pointers-to-char.
#include<stdio.h> int main(int argc, char *argv[]) { printf(&quot;No. of Argument::%d&quot;,argc); int cnt=argc-1; while(cnt>=1) { printf(&quot;\nEntered numbers are%s&quot;,argv[cnt]); cnt--; }return 0;}
#include <stdio.h> main( int argc, char *argv[] )  { if( argc == 2 )  printf(&quot;The argument supplied is %s\n&quot;, argv[1]);  else if( argc > 2 ) printf(&quot;Too many arguments supplied.\n&quot;);  else printf(&quot;One argument expected.\n&quot;);  }  CS 3090: Safety Critical Programming in C
typedef struct IntNode { int value; struct IntNode *next; } INTNODE; INTNODE *search_list(INTNODE *node, int const key) { while (!node) { if (node->value == key) break; node = node->next; } return node; } CS 3090: Safety Critical Programming in C OK, but it only works for nodes containing integer data. If you want a list of strings, you’ll need to define a new type and new function.
typedef struct Node { void *value; struct Node *next; } NODE; void construct_node(NODE *node, void *value, NODE *next) { node->value = value; node->next = next; } NODE *new_node(void *value, NODE *next) { NODE *node = (NODE *)malloc(sizeof(NODE)); construct_node(node, value, next); return node; } CS 3090: Safety Critical Programming in C void*  is compatible with any pointer type. So, this member can hold (a pointer to) any value!
What is it that makes the old  search_list  only work for integers? The  key  parameter is of type  int The  ==  operator is used to compare  int  values – but  ==  will not work for many types (e.g. structs, strings) A solution: pass in an additional argument – a comparison function! Programmer must supply a comparison function that’s appropriate for the data type being stored in the nodes This function argument is called a  callback function : Caller passes in a pointer to a function Callee then “calls back” to the caller-supplied function CS 3090: Safety Critical Programming in C
NODE *search_list(NODE *node, void const *key, int (*compare)(void const *, void const *)) { while (node) { if (!compare(node->value, key)) break; node = node->next; } return node; } CS 3090: Safety Critical Programming in C Assumption:  compare  returns zero if its parameter values are equal; nonzero otherwise
If our nodes hold strings, we have a compare function already defined:  strcmp  or  strncmpy #include <string.h> … match = search_list(root, &quot;key&quot;, &strcmp); CS 3090: Safety Critical Programming in C Note: you may get a warning, since  strcmp  is not strictly of the right type: its parameters are of type  char *  rather than  void * &  is optional here – compiler will implicitly take the address
If our nodes hold other kinds of data, we may need to “roll our own” compare function int compare_ints(void const *a, void const *b) { const int ia = *(int *)a, ib = *(int *)b; return ia != ib; } … match = search_list(root, key, &compare_ints); CS 3090: Safety Critical Programming in C
In some cases, a nice alternative to long, repetitive switch statements, like this: double add(double, double); double sub(double, double); double mul(double, double); double div(double, double); switch(oper) { case ADD: result = add(op1, op2); break; case SUB: result = sub(op1, op2); break; case MUL: result = mul(op1, op2); break; case DIV: result = div(op1, op2); break; } CS 3090: Safety Critical Programming in C
Jump table alternative: double add(double, double); double sub(double, double); double mul(double, double); double div(double, double); double (*oper_func[])(double, double) = { add, sub, mul, div }; result = oper_func[oper](op1, op2); CS 3090: Safety Critical Programming in C Array of pointers to functions. Each function takes two  double s and returns a  double
What if uninitialized function pointer value is accessed? Safest outcome: memory error, and program is terminated But what if the “garbage” value is a valid address? Worst case: address contains program instruction – execution continues, with random results Hard to trace the cause of the erroneous behavior CS 3090: Safety Critical Programming in C
C programs can be called from the command line, with certain arguments entered along with the program name: e.g. Registration program register You may register with an existing ID by the – i  option: register -i  ID Otherwise, an ID will be generated CS 3090: Safety Critical Programming in C
main  function can be declared with two arguments: int main(int argc, char **argv) argc  holds the number of arguments argv  is an array of strings: the  n th command line string is stored at  argv[n-1]   register -i wallace CS 3090: Safety Critical Programming in C 3 argc argc [0] [1] [2] [3] NUL
int main(int argc, char **argv) { char id[ID_LIMIT]; switch(argc) { case 1: generate_ID(id); break; case 3: if (strcmp(argv[1], &quot;-i&quot;) exit(INVALID_ARG); strcpy(id, argv[2]); break; default: exit(INVALID_ARG_COUNT); } register(id); } CS 3090: Safety Critical Programming in C
The Function Pointer Tutorials.  http://www.newty.de/fpt/index.html   CS 3090: Safety Critical Programming in C

More Related Content

PPT
Hooking signals and dumping the callstack
PPT
Advanced pointers
PPSX
Pointers
PDF
Types of pointer in C
PDF
See through C
PPT
Advanced C programming
PPTX
Dynamic Memory Allocation in C
PPT
Void pointer in c
Hooking signals and dumping the callstack
Advanced pointers
Pointers
Types of pointer in C
See through C
Advanced C programming
Dynamic Memory Allocation in C
Void pointer in c

What's hot (19)

DOC
Assignment c programming
DOCX
PDF
C Programming Assignment
PPTX
Unit 8. Pointers
PPT
Chapter Eight(2)
PPTX
Pointers in C
PPT
Code generator
PPT
Savitch ch 08
PPTX
Pointers in C Language
PDF
Lecturer23 pointersin c.ppt
PPT
Introduction to pointers and memory management in C
PPT
C pointers
PPT
PPS
C programming session 05
PDF
Pointers_c
PPT
Intermediate code generation (Compiler Design)
PPTX
CPP Programming Homework Help
PPT
String & its application
Assignment c programming
C Programming Assignment
Unit 8. Pointers
Chapter Eight(2)
Pointers in C
Code generator
Savitch ch 08
Pointers in C Language
Lecturer23 pointersin c.ppt
Introduction to pointers and memory management in C
C pointers
C programming session 05
Pointers_c
Intermediate code generation (Compiler Design)
CPP Programming Homework Help
String & its application
Ad

Viewers also liked (7)

PDF
9. pointer, pointer & function
PPTX
Data structure lecture 1
PPTX
PPT
6 pointers functions
PPT
Pointers in C
PDF
C Pointers
PPTX
Human values & professional ethics
9. pointer, pointer & function
Data structure lecture 1
6 pointers functions
Pointers in C
C Pointers
Human values & professional ethics
Ad

Similar to Advanced+pointers (20)

PPTX
UNIT 4 POINTERS.pptx pointers pptx for basic c language
PDF
07 -pointers_and_memory_alloc
PPT
Pointers definition syntax structure use
PPT
Chapter09-10 Pointers and operations .PPT
PPT
Chapter09-10.PPT
PDF
Pointers In C
PDF
Pointers In C
PPT
Pointers C programming
PPTX
Pointers and Dynamic Memory Allocation
PPT
l7-pointers.ppt
PPTX
Input output functions
PPT
358 33 powerpoint-slides_3-pointers_chapter-3
PPTX
pointers_final.pptxxxxxxxxxxxxxxxxxxxxxx
PDF
C programming session8
PDF
C programming session8
PDF
C Programming - Refresher - Part III
PDF
Pointers
PDF
Pointers c imp
PDF
Memory Management for C and C++ _ language
UNIT 4 POINTERS.pptx pointers pptx for basic c language
07 -pointers_and_memory_alloc
Pointers definition syntax structure use
Chapter09-10 Pointers and operations .PPT
Chapter09-10.PPT
Pointers In C
Pointers In C
Pointers C programming
Pointers and Dynamic Memory Allocation
l7-pointers.ppt
Input output functions
358 33 powerpoint-slides_3-pointers_chapter-3
pointers_final.pptxxxxxxxxxxxxxxxxxxxxxx
C programming session8
C programming session8
C Programming - Refresher - Part III
Pointers
Pointers c imp
Memory Management for C and C++ _ language

Recently uploaded (20)

PDF
3rd Neelam Sanjeevareddy Memorial Lecture.pdf
PPTX
PPT- ENG7_QUARTER1_LESSON1_WEEK1. IMAGERY -DESCRIPTIONS pptx.pptx
PPTX
PPH.pptx obstetrics and gynecology in nursing
PPTX
Institutional Correction lecture only . . .
PDF
Pre independence Education in Inndia.pdf
PDF
Complications of Minimal Access Surgery at WLH
PDF
Sports Quiz easy sports quiz sports quiz
PDF
Module 4: Burden of Disease Tutorial Slides S2 2025
PPTX
Cell Structure & Organelles in detailed.
PDF
2.FourierTransform-ShortQuestionswithAnswers.pdf
PDF
Chapter 2 Heredity, Prenatal Development, and Birth.pdf
PDF
Anesthesia in Laparoscopic Surgery in India
PDF
Abdominal Access Techniques with Prof. Dr. R K Mishra
PPTX
Microbial diseases, their pathogenesis and prophylaxis
PDF
Classroom Observation Tools for Teachers
PDF
01-Introduction-to-Information-Management.pdf
PPTX
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
PDF
O7-L3 Supply Chain Operations - ICLT Program
PDF
Insiders guide to clinical Medicine.pdf
PDF
BÀI TẬP BỔ TRỢ 4 KỸ NĂNG TIẾNG ANH 9 GLOBAL SUCCESS - CẢ NĂM - BÁM SÁT FORM Đ...
3rd Neelam Sanjeevareddy Memorial Lecture.pdf
PPT- ENG7_QUARTER1_LESSON1_WEEK1. IMAGERY -DESCRIPTIONS pptx.pptx
PPH.pptx obstetrics and gynecology in nursing
Institutional Correction lecture only . . .
Pre independence Education in Inndia.pdf
Complications of Minimal Access Surgery at WLH
Sports Quiz easy sports quiz sports quiz
Module 4: Burden of Disease Tutorial Slides S2 2025
Cell Structure & Organelles in detailed.
2.FourierTransform-ShortQuestionswithAnswers.pdf
Chapter 2 Heredity, Prenatal Development, and Birth.pdf
Anesthesia in Laparoscopic Surgery in India
Abdominal Access Techniques with Prof. Dr. R K Mishra
Microbial diseases, their pathogenesis and prophylaxis
Classroom Observation Tools for Teachers
01-Introduction-to-Information-Management.pdf
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
O7-L3 Supply Chain Operations - ICLT Program
Insiders guide to clinical Medicine.pdf
BÀI TẬP BỔ TRỢ 4 KỸ NĂNG TIẾNG ANH 9 GLOBAL SUCCESS - CẢ NĂM - BÁM SÁT FORM Đ...

Advanced+pointers

  • 2. Declaration: returnType (*varName)(parameterTypes); Examples: int (*f)(int, float); int *(*g[])(int, float); int *(*g[])(int, float); pointer to a function that takes an integer argument and a float argument and returns an integer pointer to a function that takes an integer argument and a float argument and returns a pointer to an integer An array of pointers to functions – Each function takes an integer argument and a float argument and returns a pointer to an integer
  • 3. Function Pointers are pointers, i.e. variables, which point to the address of a function. A function pointer always points to a function with a specific signature! Thus all functions, you want to use with the same function pointer, must have the  same parameters and return-type! Example: Task to perform one of the four basic arithmetic operation Solution: i)The task is first solved using a switch- statement. ii)Then it is shown, how the same can be done using a function pointer CS 3090: Safety Critical Programming in C
  • 4. Void Pointers CS 3090: Safety Critical Programming in C
  • 5.   void  pointer seems to be of limited when combined with the ability to cast such a pointer to another type, they turn out to be quite useful and flexible . CS 3090: Safety Critical Programming in C
  • 6. int * const ptr2  indicates that  ptr2 is a pointer which is constant. This means that ptr2 cannot be made to point to another integer. However the integer pointed by ptr2 can be changed. For eg. int x=10, y=20; int * const ptr=&x; *ptr=30; ptr=&y; //illegal Where as a Pointer to constant is  const int * ptr1  indicates that ptr1 is a pointer that points to a constant integer. The integer is constant and cannot be changed. However, the pointer ptr1 can be made to point to some other integer. For eg. int x=10; y=20; const int *ptr=&x; x=20; ptr=&y; *ptr=30; //Illegal
  • 7. 1. Near pointer 2. Far pointer 3. Huge pointer CS 3090: Safety Critical Programming in C
  • 8. Entire RAM has divided in numbers of equal parts, which are known as memory cells. Following diagram represents the 256 MB RAM. Each cell can store one-byte data. Data are stored in the  binary number system. That is a character data reserves one memory cell while floating data reserves four memory cells. Each memory cell has unique address. Address is always in whole number and must be in increasing order. CS 3090: Safety Critical Programming in C
  • 10. int a = 4; Q. If you know memory address of first cell is 0x5000 then  what would be the memory address of next memory cell? A. It will 5001 since integer data always stores at  continuous memory location and as we know memory address always in increasing order. CS 3090: Safety Critical Programming in C
  • 11. RAM has divided into two parts: (1)        Extended memory (useless) (2)        Residence memory   When any program is executed it is stored in the residence memory. All the c variables are stored in the residence memory. Depending upon the compiler the residence memory is defined. For example. In Turbo C 3.0 its 1MB. In turbo C 3.0, 20 bits address of the memory cell is known as physical address or real address. In 20 bits, we can represent address   from 0x00000 to 0xFFFFF. That is all c variables must have memory address within this range.
  • 12. CS 3090: Safety Critical Programming in C
  • 13. A C programmer cannot not decides what will be the memory address of any variables.
  • 14. Residential memory of RAM of size 1MB has divided into 16 equal parts. These parts is called segment. Each segment has size is 64 KB. 16 * 64 KB = 1 MB CS 3090: Safety Critical Programming in C
  • 16. Note: In turbo c 3.0 physical addresses of any variables are stored in the 20 bits. But we have not any pointers  of size 20 bits. So pointers cannot access whole residence memory address. To solve this problem we there are three types pointers in c language. They are 1. Near pointer 2. Far pointer 3. Huge pointer CS 3090: Safety Critical Programming in C
  • 17. Each segment has divided into two parts. 1. Segment no (4 bit) 2. Offset address (16 bit) CS 3090: Safety Critical Programming in C
  • 18. #include<stdio.h> int main(){ int x; printf(&quot;%u &quot;,&x); //To print offset address printf(&quot;%p &quot;,x); //To print segment address printf(&quot;%p &quot;,&x); //To print offset address printf(&quot;%fp &quot;,&x); //To print segment address : offset address return 0;} CS 3090: Safety Critical Programming in C
  • 19. All the segments are used for specific purpose. Like segment number 15 is used for ROM, segment number 14 is used for BIOS etc. CS 3090: Safety Critical Programming in C
  • 20. CS 3090: Safety Critical Programming in C
  • 21. Segment number eight has special name which is known as data segment. This segment has been divided into four parts. This is very important for c programming CS 3090: Safety Critical Programming in C
  • 22. 1. Stack area:- All automatic variables are created into stack area.Default storage class of any local variable is auto.This variable may be int, char, float, array, pointer, struct, union etc.It also return function argument and return address.It follow LIFO data structure. It has two part one for initialize variable another for non-initialize variable.All initialize variable are more nearer than uninitialized variable and vice versa. 2. Data area : All static and extern variable are created in the data area. CS 3090: Safety Critical Programming in C
  • 23. 3. Heap area: Malloc and calloc always allocate memory in the heap area.It is used for dynamic memory allocation.It’s size depends upon free space in the memory. 4. Code area : Function pointer can only access code area.Size of this area is always fixed and it is read only area CS 3090: Safety Critical Programming in C
  • 24. The pointer which can points only 64KB data segment or segment number 8 is known as near pointer. CS 3090: Safety Critical Programming in C
  • 25. The limitation is that you can only access 64kb of data at a time, because that is the size of a segment - 64kb
  • 26. The pointer which can point or access whole the residence memory of RAM i.e. which can access all 16 segments is known as far pointer. CS 3090: Safety Critical Programming in C Far Pointer
  • 27. 09/27/11 CS 3090: Safety Critical Programming in C
  • 28. Size of far Pointer is 4 byte or 32 bit #include<stdio.h> int main(){ int x=10; int far *ptr; ptr=&x; printf(&quot;%d&quot;,sizeof ptr); return 0;} Output: 4 CS 3090: Safety Critical Programming in C
  • 29. CS 3090: Safety Critical Programming in C Same as the far Pointer They are normalized.
  • 30. Size of far Pointer is 4 byte or 32 bit #include<stdio.h> int main(){ int x=10; int far *ptr; ptr=&x; printf(&quot;%d&quot;,sizeof ptr); return 0;} Output: 4 CS 3090: Safety Critical Programming in C
  • 31. int main(int argc, char *argv[]) { ... } When main is called, argc will be a count of the number of command-line arguments, and argv will be an array of the arguments themselves. Since each word is a string which is represented as a pointer-to-char, argv is an array-of-pointers-to-char.
  • 32. #include<stdio.h> int main(int argc, char *argv[]) { printf(&quot;No. of Argument::%d&quot;,argc); int cnt=argc-1; while(cnt>=1) { printf(&quot;\nEntered numbers are%s&quot;,argv[cnt]); cnt--; }return 0;}
  • 33. #include <stdio.h> main( int argc, char *argv[] ) { if( argc == 2 ) printf(&quot;The argument supplied is %s\n&quot;, argv[1]); else if( argc > 2 ) printf(&quot;Too many arguments supplied.\n&quot;); else printf(&quot;One argument expected.\n&quot;); } CS 3090: Safety Critical Programming in C
  • 34. typedef struct IntNode { int value; struct IntNode *next; } INTNODE; INTNODE *search_list(INTNODE *node, int const key) { while (!node) { if (node->value == key) break; node = node->next; } return node; } CS 3090: Safety Critical Programming in C OK, but it only works for nodes containing integer data. If you want a list of strings, you’ll need to define a new type and new function.
  • 35. typedef struct Node { void *value; struct Node *next; } NODE; void construct_node(NODE *node, void *value, NODE *next) { node->value = value; node->next = next; } NODE *new_node(void *value, NODE *next) { NODE *node = (NODE *)malloc(sizeof(NODE)); construct_node(node, value, next); return node; } CS 3090: Safety Critical Programming in C void* is compatible with any pointer type. So, this member can hold (a pointer to) any value!
  • 36. What is it that makes the old search_list only work for integers? The key parameter is of type int The == operator is used to compare int values – but == will not work for many types (e.g. structs, strings) A solution: pass in an additional argument – a comparison function! Programmer must supply a comparison function that’s appropriate for the data type being stored in the nodes This function argument is called a callback function : Caller passes in a pointer to a function Callee then “calls back” to the caller-supplied function CS 3090: Safety Critical Programming in C
  • 37. NODE *search_list(NODE *node, void const *key, int (*compare)(void const *, void const *)) { while (node) { if (!compare(node->value, key)) break; node = node->next; } return node; } CS 3090: Safety Critical Programming in C Assumption: compare returns zero if its parameter values are equal; nonzero otherwise
  • 38. If our nodes hold strings, we have a compare function already defined: strcmp or strncmpy #include <string.h> … match = search_list(root, &quot;key&quot;, &strcmp); CS 3090: Safety Critical Programming in C Note: you may get a warning, since strcmp is not strictly of the right type: its parameters are of type char * rather than void * & is optional here – compiler will implicitly take the address
  • 39. If our nodes hold other kinds of data, we may need to “roll our own” compare function int compare_ints(void const *a, void const *b) { const int ia = *(int *)a, ib = *(int *)b; return ia != ib; } … match = search_list(root, key, &compare_ints); CS 3090: Safety Critical Programming in C
  • 40. In some cases, a nice alternative to long, repetitive switch statements, like this: double add(double, double); double sub(double, double); double mul(double, double); double div(double, double); switch(oper) { case ADD: result = add(op1, op2); break; case SUB: result = sub(op1, op2); break; case MUL: result = mul(op1, op2); break; case DIV: result = div(op1, op2); break; } CS 3090: Safety Critical Programming in C
  • 41. Jump table alternative: double add(double, double); double sub(double, double); double mul(double, double); double div(double, double); double (*oper_func[])(double, double) = { add, sub, mul, div }; result = oper_func[oper](op1, op2); CS 3090: Safety Critical Programming in C Array of pointers to functions. Each function takes two double s and returns a double
  • 42. What if uninitialized function pointer value is accessed? Safest outcome: memory error, and program is terminated But what if the “garbage” value is a valid address? Worst case: address contains program instruction – execution continues, with random results Hard to trace the cause of the erroneous behavior CS 3090: Safety Critical Programming in C
  • 43. C programs can be called from the command line, with certain arguments entered along with the program name: e.g. Registration program register You may register with an existing ID by the – i option: register -i ID Otherwise, an ID will be generated CS 3090: Safety Critical Programming in C
  • 44. main function can be declared with two arguments: int main(int argc, char **argv) argc holds the number of arguments argv is an array of strings: the n th command line string is stored at argv[n-1] register -i wallace CS 3090: Safety Critical Programming in C 3 argc argc [0] [1] [2] [3] NUL
  • 45. int main(int argc, char **argv) { char id[ID_LIMIT]; switch(argc) { case 1: generate_ID(id); break; case 3: if (strcmp(argv[1], &quot;-i&quot;) exit(INVALID_ARG); strcpy(id, argv[2]); break; default: exit(INVALID_ARG_COUNT); } register(id); } CS 3090: Safety Critical Programming in C
  • 46. The Function Pointer Tutorials. http://www.newty.de/fpt/index.html CS 3090: Safety Critical Programming in C