principles of programming languages - computer sciencelou/314-f04-slides/topic05_imperativeb.pdfcs...
TRANSCRIPT
![Page 1: Principles of Programming Languages - Computer Sciencelou/314-f04-slides/topic05_imperativeB.pdfCS 314, LS, BR, LTM: Imperative Programming 11 Heap Storage void *malloc (size_t n)](https://reader031.vdocuments.mx/reader031/viewer/2022040405/5e9c5b939c0d1725fc3aee68/html5/thumbnails/1.jpg)
CS 314, LS, BR, LTM: Imperative Programming 1
Principles ofPrinciples ofProgramming LanguagesProgramming Languages
Topic: Imperative Programming IIProfessor Lou Steinberg
Fall 2004
![Page 2: Principles of Programming Languages - Computer Sciencelou/314-f04-slides/topic05_imperativeB.pdfCS 314, LS, BR, LTM: Imperative Programming 11 Heap Storage void *malloc (size_t n)](https://reader031.vdocuments.mx/reader031/viewer/2022040405/5e9c5b939c0d1725fc3aee68/html5/thumbnails/2.jpg)
CS 314, LS, BR, LTM: Imperative Programming 2
ReviewReview
• Imperative programming:– based on underlying machine: RAM, thread of control– variable: a memory location– assignment
• L-values and R-values• Pointers
– * and &• #INCLUDE
– #DEFINE STACKSIZE = 10;• printf
![Page 3: Principles of Programming Languages - Computer Sciencelou/314-f04-slides/topic05_imperativeB.pdfCS 314, LS, BR, LTM: Imperative Programming 11 Heap Storage void *malloc (size_t n)](https://reader031.vdocuments.mx/reader031/viewer/2022040405/5e9c5b939c0d1725fc3aee68/html5/thumbnails/3.jpg)
CS 314, LS, BR, LTM: Imperative Programming 3
L- and R-valuesL- and R-values
contents of variable that ppoints to
contents of p*p
address of variable aillegal&a
contents of paddress of ppcontents of 1st element of billegal*baddress of 1st element of billegalb
b[2]
a
12
contents of 3rd element of baddress of 3rd element of b
contents of variable aaddress of variable a12illegalR-valueL-value
int a; int [10] b; int *p
![Page 4: Principles of Programming Languages - Computer Sciencelou/314-f04-slides/topic05_imperativeB.pdfCS 314, LS, BR, LTM: Imperative Programming 11 Heap Storage void *malloc (size_t n)](https://reader031.vdocuments.mx/reader031/viewer/2022040405/5e9c5b939c0d1725fc3aee68/html5/thumbnails/4.jpg)
CS 314, LS, BR, LTM: Imperative Programming 4
Excerpt from List in JavaExcerpt from List in Javapublic class List extends Object {protected Object element;protected List subList; /** * Create an new List, initially empty. */ public List() {
element = null;subList = null;
}
//cons operation public List(Object newElement,List oldList){
element = newElement;subList = oldList;
} }
![Page 5: Principles of Programming Languages - Computer Sciencelou/314-f04-slides/topic05_imperativeB.pdfCS 314, LS, BR, LTM: Imperative Programming 11 Heap Storage void *malloc (size_t n)](https://reader031.vdocuments.mx/reader031/viewer/2022040405/5e9c5b939c0d1725fc3aee68/html5/thumbnails/5.jpg)
CS 314, LS, BR, LTM: Imperative Programming 5
How List building works?How List building works?
List p = new List();
“a”
List q = new List(“a”,p);
“a”“b”
List(“b”,q);
![Page 6: Principles of Programming Languages - Computer Sciencelou/314-f04-slides/topic05_imperativeB.pdfCS 314, LS, BR, LTM: Imperative Programming 11 Heap Storage void *malloc (size_t n)](https://reader031.vdocuments.mx/reader031/viewer/2022040405/5e9c5b939c0d1725fc3aee68/html5/thumbnails/6.jpg)
CS 314, LS, BR, LTM: Imperative Programming 6
list2.c list2.c/*sample program to write a linear linked list of integers
built like in Java, adding new elements on the front*/#include<stdio.h>/*this makes these definitions and variables global*/void *malloc();typedef struct cell listcell;struct cell{
int num;listcell *next;
};listcell *head, *ele, *p;
![Page 7: Principles of Programming Languages - Computer Sciencelou/314-f04-slides/topic05_imperativeB.pdfCS 314, LS, BR, LTM: Imperative Programming 11 Heap Storage void *malloc (size_t n)](https://reader031.vdocuments.mx/reader031/viewer/2022040405/5e9c5b939c0d1725fc3aee68/html5/thumbnails/7.jpg)
CS 314, LS, BR, LTM: Imperative Programming 7
list2.c, cont.list2.c, cont.void main(void){ int j;/*create first node in list*/
head = (listcell *) malloc(sizeof (listcell));head->next = NULL;
castAllocates heap storage
/*now create entries in list of numbers from 1 to 10*/head->num = 1;for (j=2; j<11; j++){ ele = (listcell *) malloc(sizeof (listcell));
ele->num = j;ele->next =head; /***/head = ele;
}/*now traverse the list and print the elements*/
for (p=head; p!=NULL; p=p->next)printf("%d ",p->num);
printf("\n");} (*head).next is same as head->next
![Page 8: Principles of Programming Languages - Computer Sciencelou/314-f04-slides/topic05_imperativeB.pdfCS 314, LS, BR, LTM: Imperative Programming 11 Heap Storage void *malloc (size_t n)](https://reader031.vdocuments.mx/reader031/viewer/2022040405/5e9c5b939c0d1725fc3aee68/html5/thumbnails/8.jpg)
CS 314, LS, BR, LTM: Imperative Programming 8
list2.clist2.chead
1
2 1ele
ele2 13
at /***/ in 1st iteration
at /***/ in 2nd iteration
head
head
for (j=2; j<11; j++){ ele=/* &(new listcell*/
ele->num = j;ele->next =head; /***/head = ele;
}
head->num = 1;
![Page 9: Principles of Programming Languages - Computer Sciencelou/314-f04-slides/topic05_imperativeB.pdfCS 314, LS, BR, LTM: Imperative Programming 11 Heap Storage void *malloc (size_t n)](https://reader031.vdocuments.mx/reader031/viewer/2022040405/5e9c5b939c0d1725fc3aee68/html5/thumbnails/9.jpg)
CS 314, LS, BR, LTM: Imperative Programming 9
list2.c outputlist2.c outputscherzo!c> gcc list2.cscherzo!c> ./a.out10 9 8 7 6 5 4 3 2 1scherzo!c>
![Page 10: Principles of Programming Languages - Computer Sciencelou/314-f04-slides/topic05_imperativeB.pdfCS 314, LS, BR, LTM: Imperative Programming 11 Heap Storage void *malloc (size_t n)](https://reader031.vdocuments.mx/reader031/viewer/2022040405/5e9c5b939c0d1725fc3aee68/html5/thumbnails/10.jpg)
CS 314, LS, BR, LTM: Imperative Programming 10
Review:Review: Stack Stack vs vs HeapHeap
• Procedure activations,statically allocated localvariables, parameter values
• Lifetime same as block inwhich variables are declared
• Stack frame with eachinvocation of procedure
• Dynamically allocated datastructures, whose size maynot be known in advance
• Lifetime extends beyondblock in which they arecreated
• Must be explicitly freed orgarbage collected
![Page 11: Principles of Programming Languages - Computer Sciencelou/314-f04-slides/topic05_imperativeB.pdfCS 314, LS, BR, LTM: Imperative Programming 11 Heap Storage void *malloc (size_t n)](https://reader031.vdocuments.mx/reader031/viewer/2022040405/5e9c5b939c0d1725fc3aee68/html5/thumbnails/11.jpg)
CS 314, LS, BR, LTM: Imperative Programming 11
Heap StorageHeap Storagevoid *malloc (size_t n)
– returns pointer to block of contiguous storage of n bytes (chars), ifpossible
– if not enough memory left for allocation, malloc returns a NULLpointer
• So you ALWAYS have to check the return value– to allocate storage of a different type requires sending malloc the
proper amount of bytes needed and casting the return pointer valueappropriately
head = (listcell *) malloc(sizeof (listcell));
![Page 12: Principles of Programming Languages - Computer Sciencelou/314-f04-slides/topic05_imperativeB.pdfCS 314, LS, BR, LTM: Imperative Programming 11 Heap Storage void *malloc (size_t n)](https://reader031.vdocuments.mx/reader031/viewer/2022040405/5e9c5b939c0d1725fc3aee68/html5/thumbnails/12.jpg)
CS 314, LS, BR, LTM: Imperative Programming 12
listwithfreelistwithfree.c.c
Almost same declarations as list2.c
/*sample program to write a linear linked list of integersbuilt like in Java, adding new elements on the front*/
#include<stdio.h>/*this makes these definitions and variables global*/void *malloc();void free();typedef struct cell listcell;struct cell{
int num;listcell *next;
};listcell *head, *ele, *p;
![Page 13: Principles of Programming Languages - Computer Sciencelou/314-f04-slides/topic05_imperativeB.pdfCS 314, LS, BR, LTM: Imperative Programming 11 Heap Storage void *malloc (size_t n)](https://reader031.vdocuments.mx/reader031/viewer/2022040405/5e9c5b939c0d1725fc3aee68/html5/thumbnails/13.jpg)
CS 314, LS, BR, LTM: Imperative Programming 13
listwithfreelistwithfree.c, cont..c, cont.main(void){ int j;/*create first node in list*/
head = (listcell *) malloc(sizeof (listcell));/*now create other entries in list of numbers from 1 to
10*/head->num = 1;for (j=2; j<11; j++){ ele = (listcell *) malloc(sizeof (listcell));
ele->num = j;ele->next =head; /***/head = ele;
} printf(" values in the list: ");/*now traverse the list and print the elements*/
for (p=head; p!=NULL; p=p->next)printf("%d ",p->num);
printf("\n");} Same building of the list
and printing it out as list2.c
![Page 14: Principles of Programming Languages - Computer Sciencelou/314-f04-slides/topic05_imperativeB.pdfCS 314, LS, BR, LTM: Imperative Programming 11 Heap Storage void *malloc (size_t n)](https://reader031.vdocuments.mx/reader031/viewer/2022040405/5e9c5b939c0d1725fc3aee68/html5/thumbnails/14.jpg)
CS 314, LS, BR, LTM: Imperative Programming 14
listwithfreelistwithfree.c, cont..c, cont./*now delete the first 2 elements of the list and free
their storage */ele = head->next; /*1*/free (head); /* free 1st list element storage*/head = ele;ele = head->next; /*2*/
free (head); /* free 2nd list element storage*/head = ele; /*3*/
/*now traverse the list and print the elements*/ printf(" values in list after two free's: ");
for (p=head; p!=NULL; p=p->next)printf("%d ",p->num);
printf("\n");
}
![Page 15: Principles of Programming Languages - Computer Sciencelou/314-f04-slides/topic05_imperativeB.pdfCS 314, LS, BR, LTM: Imperative Programming 11 Heap Storage void *malloc (size_t n)](https://reader031.vdocuments.mx/reader031/viewer/2022040405/5e9c5b939c0d1725fc3aee68/html5/thumbnails/15.jpg)
CS 314, LS, BR, LTM: Imperative Programming 15
TraceTrace
head9 810
ele
...
9 8
head
...
ele
After ele = head->next; /*1*/
After free (head);head = ele; ele = head->next; /*2*/
![Page 16: Principles of Programming Languages - Computer Sciencelou/314-f04-slides/topic05_imperativeB.pdfCS 314, LS, BR, LTM: Imperative Programming 11 Heap Storage void *malloc (size_t n)](https://reader031.vdocuments.mx/reader031/viewer/2022040405/5e9c5b939c0d1725fc3aee68/html5/thumbnails/16.jpg)
CS 314, LS, BR, LTM: Imperative Programming 16
listwithfreelistwithfree.c, cont..c, cont.
/* output221 remus!c> a.out values in the list: 10 9 8 7 6 5 4 3 2 1 values in list after two free's: 8 7 6 5 4 3 2 1 222 remus!c> */
8 ...
ele
head
After free (head); head = ele; /*3*/
9 8
head
...
ele
![Page 17: Principles of Programming Languages - Computer Sciencelou/314-f04-slides/topic05_imperativeB.pdfCS 314, LS, BR, LTM: Imperative Programming 11 Heap Storage void *malloc (size_t n)](https://reader031.vdocuments.mx/reader031/viewer/2022040405/5e9c5b939c0d1725fc3aee68/html5/thumbnails/17.jpg)
CS 314, LS, BR, LTM: Imperative Programming 17
FunctionsFunctions
• Prototype:int mult(int, int); int square(int n);– often in a *.h or “header” file– used by compiler for type checking
• Definition:int square(int n) {return n*n;}
• Invocation:int b = 3; c = square(b);
(formal)parameter
argument
![Page 18: Principles of Programming Languages - Computer Sciencelou/314-f04-slides/topic05_imperativeB.pdfCS 314, LS, BR, LTM: Imperative Programming 11 Heap Storage void *malloc (size_t n)](https://reader031.vdocuments.mx/reader031/viewer/2022040405/5e9c5b939c0d1725fc3aee68/html5/thumbnails/18.jpg)
CS 314, LS, BR, LTM: Imperative Programming 18
FunctionsFunctions
• Parameter Passing uses “Call by Value”– Value of actual argument is copied into formal parameter– Example:
void swap(int a,int b) {int temp; temp=a; a=b; b=temp;}
...int x=3; int y=5;swap(x,y);printf(“%d %d”,x,y); --> 3 5 !?!
– Why?
![Page 19: Principles of Programming Languages - Computer Sciencelou/314-f04-slides/topic05_imperativeB.pdfCS 314, LS, BR, LTM: Imperative Programming 11 Heap Storage void *malloc (size_t n)](https://reader031.vdocuments.mx/reader031/viewer/2022040405/5e9c5b939c0d1725fc3aee68/html5/thumbnails/19.jpg)
CS 314, LS, BR, LTM: Imperative Programming 19
FunctionsFunctions
• To get the effect of “Call by Reference” use pointers– Example:
void swap(int *a, int *b) {int temp; temp=*a; *a=*b; *b=temp;}...int x=3;int y=5;swap( &x, &y );printf(“%d %d”,x,y); --> 5 3
![Page 20: Principles of Programming Languages - Computer Sciencelou/314-f04-slides/topic05_imperativeB.pdfCS 314, LS, BR, LTM: Imperative Programming 11 Heap Storage void *malloc (size_t n)](https://reader031.vdocuments.mx/reader031/viewer/2022040405/5e9c5b939c0d1725fc3aee68/html5/thumbnails/20.jpg)
CS 314, LS, BR, LTM: Imperative Programming 20
scanfscanf
int i;double x;scanf(“%i %lf”, &i, &x);
remus> man scanf
![Page 21: Principles of Programming Languages - Computer Sciencelou/314-f04-slides/topic05_imperativeB.pdfCS 314, LS, BR, LTM: Imperative Programming 11 Heap Storage void *malloc (size_t n)](https://reader031.vdocuments.mx/reader031/viewer/2022040405/5e9c5b939c0d1725fc3aee68/html5/thumbnails/21.jpg)
CS 314, LS, BR, LTM: Imperative Programming 21
StructuresStructures
• Structure: Aggregate object with named fields– Declaration: struct EMPLOYEE { int age; double payrate; } joe, mary; struct EMPLOYEE bill = {35, 65000.00};– Accessed as: joe.age = 45; bill.payrate *= 1.1;
![Page 22: Principles of Programming Languages - Computer Sciencelou/314-f04-slides/topic05_imperativeB.pdfCS 314, LS, BR, LTM: Imperative Programming 11 Heap Storage void *malloc (size_t n)](https://reader031.vdocuments.mx/reader031/viewer/2022040405/5e9c5b939c0d1725fc3aee68/html5/thumbnails/22.jpg)
CS 314, LS, BR, LTM: Imperative Programming 22
StructuresStructures
• Structure may contain actual fields, as opposed toreferencesstruct STACK { int top; int contents[5]; } stack1;struct STACK { int top; int *contents; } stack1;
![Page 23: Principles of Programming Languages - Computer Sciencelou/314-f04-slides/topic05_imperativeB.pdfCS 314, LS, BR, LTM: Imperative Programming 11 Heap Storage void *malloc (size_t n)](https://reader031.vdocuments.mx/reader031/viewer/2022040405/5e9c5b939c0d1725fc3aee68/html5/thumbnails/23.jpg)
CS 314, LS, BR, LTM: Imperative Programming 23
StructuresStructures
• Defining new types:typedef float Celsius;typedef float Fahrenheit;
enum {BROWN, BLOND} hisHair, herHair;
typedef enum {BLACK, BROWN, RED, BLOND, GRAY} HairColors;
![Page 24: Principles of Programming Languages - Computer Sciencelou/314-f04-slides/topic05_imperativeB.pdfCS 314, LS, BR, LTM: Imperative Programming 11 Heap Storage void *malloc (size_t n)](https://reader031.vdocuments.mx/reader031/viewer/2022040405/5e9c5b939c0d1725fc3aee68/html5/thumbnails/24.jpg)
CS 314, LS, BR, LTM: Imperative Programming 24
StructuresStructures
• Defining new structure types:typedef struct { float x-coord; float y-coord;} Point;
struct POLYGON { Point vertices[10]; int N;} p;
![Page 25: Principles of Programming Languages - Computer Sciencelou/314-f04-slides/topic05_imperativeB.pdfCS 314, LS, BR, LTM: Imperative Programming 11 Heap Storage void *malloc (size_t n)](https://reader031.vdocuments.mx/reader031/viewer/2022040405/5e9c5b939c0d1725fc3aee68/html5/thumbnails/25.jpg)
CS 314, LS, BR, LTM: Imperative Programming 25
StructuresStructures
• Pointers to Structures:typedef struct { int age; double payrate; } Employee;Employee joe, *maryp;
• Accessed as:(*maryp).payrate = 75000.00;(*maryp).payrate += 5000.00;maryp->payrate += 5000.00;
![Page 26: Principles of Programming Languages - Computer Sciencelou/314-f04-slides/topic05_imperativeB.pdfCS 314, LS, BR, LTM: Imperative Programming 11 Heap Storage void *malloc (size_t n)](https://reader031.vdocuments.mx/reader031/viewer/2022040405/5e9c5b939c0d1725fc3aee68/html5/thumbnails/26.jpg)
CS 314, LS, BR, LTM: Imperative Programming 26
Recursive StructuresRecursive Structures
• This is legal:typedef struct NODE { int data; struct NODE *next;} Cell;
• These are not legal:typedef struct NODE { int data; struct NODE next;} Cell;
typedef struct { int data; Cell *next;} Cell;
![Page 27: Principles of Programming Languages - Computer Sciencelou/314-f04-slides/topic05_imperativeB.pdfCS 314, LS, BR, LTM: Imperative Programming 11 Heap Storage void *malloc (size_t n)](https://reader031.vdocuments.mx/reader031/viewer/2022040405/5e9c5b939c0d1725fc3aee68/html5/thumbnails/27.jpg)
CS 314, LS, BR, LTM: Imperative Programming 27
Memory AllocationMemory Allocation
• Remember the Stack and the Heap?• Parameters and local variables can be allocated on
the stack, as part of the stack frame: int n, *pn; pn = &n;
• But consider: Employee *maryp;
If you want to create the Employee structure that ispointed to by maryp, where does it go?
On the Heap!
![Page 28: Principles of Programming Languages - Computer Sciencelou/314-f04-slides/topic05_imperativeB.pdfCS 314, LS, BR, LTM: Imperative Programming 11 Heap Storage void *malloc (size_t n)](https://reader031.vdocuments.mx/reader031/viewer/2022040405/5e9c5b939c0d1725fc3aee68/html5/thumbnails/28.jpg)
CS 314, LS, BR, LTM: Imperative Programming 28
Memory AllocationMemory Allocation
• This is similar to the storage of lists in Scheme,except that you have to do it yourself!
• Standard allocation procedure:Employee *maryp;maryp = (Employee *) malloc( sizeof(Employee) );Note: malloc returns the NULL pointer if it cannot find
enough space.• To release memory:
free( maryp );
![Page 29: Principles of Programming Languages - Computer Sciencelou/314-f04-slides/topic05_imperativeB.pdfCS 314, LS, BR, LTM: Imperative Programming 11 Heap Storage void *malloc (size_t n)](https://reader031.vdocuments.mx/reader031/viewer/2022040405/5e9c5b939c0d1725fc3aee68/html5/thumbnails/29.jpg)
CS 314, LS, BR, LTM: Imperative Programming 29
Example: list.cExample: list.chead
1
2 1ele
ele2 13
at /***/ in 1st iteration
at /***/ in 2nd iteration
head
head
![Page 30: Principles of Programming Languages - Computer Sciencelou/314-f04-slides/topic05_imperativeB.pdfCS 314, LS, BR, LTM: Imperative Programming 11 Heap Storage void *malloc (size_t n)](https://reader031.vdocuments.mx/reader031/viewer/2022040405/5e9c5b939c0d1725fc3aee68/html5/thumbnails/30.jpg)
CS 314, LS, BR, LTM: Imperative Programming 30
Example:Example: listwithfree listwithfree.c.c
head9 810
ele
...
9 8
head
...
ele
After ele = head->next; /*1*/
After free (head);head = ele; ele = head->next; /*2*/
![Page 31: Principles of Programming Languages - Computer Sciencelou/314-f04-slides/topic05_imperativeB.pdfCS 314, LS, BR, LTM: Imperative Programming 11 Heap Storage void *malloc (size_t n)](https://reader031.vdocuments.mx/reader031/viewer/2022040405/5e9c5b939c0d1725fc3aee68/html5/thumbnails/31.jpg)
CS 314, LS, BR, LTM: Imperative Programming 31
Example:Example: listwithfree listwithfree.c.c
8 ...
ele
head
After free (head); head = ele; /*3*/
9 8
head
...
ele
/* output59 scherzo!c> a.out10 9 8 7 6 5 4 3 2 18 7 6 5 4 3 2 160 scherzo!c> */
![Page 32: Principles of Programming Languages - Computer Sciencelou/314-f04-slides/topic05_imperativeB.pdfCS 314, LS, BR, LTM: Imperative Programming 11 Heap Storage void *malloc (size_t n)](https://reader031.vdocuments.mx/reader031/viewer/2022040405/5e9c5b939c0d1725fc3aee68/html5/thumbnails/32.jpg)
CS 314, LS, BR, LTM: Imperative Programming 32
Compare: List in JavaCompare: List in Javapublic class List extends Object {protected Object element;protected List subList; /** * Create a new List, initially empty. */ public List() {
element = null;subList = null;
}
/* cons operation */ public List(Object newElement, List oldList){
element = newElement;subList = oldList;
} ...}
![Page 33: Principles of Programming Languages - Computer Sciencelou/314-f04-slides/topic05_imperativeB.pdfCS 314, LS, BR, LTM: Imperative Programming 11 Heap Storage void *malloc (size_t n)](https://reader031.vdocuments.mx/reader031/viewer/2022040405/5e9c5b939c0d1725fc3aee68/html5/thumbnails/33.jpg)
CS 314, LS, BR, LTM: Imperative Programming 33
Compare: List in JavaCompare: List in Java
List p = new List();
“a”
List q = new List(“a”,p);
“a”“b”
List(“b”,q);
![Page 34: Principles of Programming Languages - Computer Sciencelou/314-f04-slides/topic05_imperativeB.pdfCS 314, LS, BR, LTM: Imperative Programming 11 Heap Storage void *malloc (size_t n)](https://reader031.vdocuments.mx/reader031/viewer/2022040405/5e9c5b939c0d1725fc3aee68/html5/thumbnails/34.jpg)
CS 314, LS, BR, LTM: Imperative Programming 34
PointersPointers vs vs. References. References• Cell and Cell* are different
• Explicit dereference operator
• Pointers needed for recursivedefinitions
• Casting results in typeconversion:
int x = (int) (&w);
• Memory management isusually performed by user
• Everything is a reference
• Dereference is implicit
• Recursive definitions areautomatic
• Casting just satisfies the typechecker
• Memory management isusually automatic
![Page 35: Principles of Programming Languages - Computer Sciencelou/314-f04-slides/topic05_imperativeB.pdfCS 314, LS, BR, LTM: Imperative Programming 11 Heap Storage void *malloc (size_t n)](https://reader031.vdocuments.mx/reader031/viewer/2022040405/5e9c5b939c0d1725fc3aee68/html5/thumbnails/35.jpg)
CS 314, LS, BR, LTM: Imperative Programming 35
Pointers to FunctionsPointers to Functions
• Syntax: int foo(int x){ … } int (*pf)(int x); pf = &foo;
• Motivation: “Polymorphic” Processing– e.g., sorting an array of integers in increasing vs.
decreasing order– e.g., sorting an array of intgers vs. an array of floats vs.
an array of Employee structs vs. ...• How can we do this?
![Page 36: Principles of Programming Languages - Computer Sciencelou/314-f04-slides/topic05_imperativeB.pdfCS 314, LS, BR, LTM: Imperative Programming 11 Heap Storage void *malloc (size_t n)](https://reader031.vdocuments.mx/reader031/viewer/2022040405/5e9c5b939c0d1725fc3aee68/html5/thumbnails/36.jpg)
CS 314, LS, BR, LTM: Imperative Programming 36
Pointers to FunctionsPointers to Functions
• Suppose Cell is defined as before, but the data fieldcould be an int, a char, a struct, or ...
• Use a “callback” function:Cell *searchlist(Cell *c, void *value, int (*compare)(void *, void *)) { for ( ; c!=NULL; c=c->next){ if ((*compare)(&(c->data), value)) break;} return c;}
![Page 37: Principles of Programming Languages - Computer Sciencelou/314-f04-slides/topic05_imperativeB.pdfCS 314, LS, BR, LTM: Imperative Programming 11 Heap Storage void *malloc (size_t n)](https://reader031.vdocuments.mx/reader031/viewer/2022040405/5e9c5b939c0d1725fc3aee68/html5/thumbnails/37.jpg)
CS 314, LS, BR, LTM: Imperative Programming 37
ArraysArrays
• Array: Typed collection of values indexed bynonnegative integers.
• Type and size must be known at compile time,except in the case of formal parameters:
int a[20]; void sort(int b[], int n);
• Arrays in C are one-dimensional: piece chess[8][8];
• Strings are arrays of characters: char msg[21] = “Enter your password:”;
![Page 38: Principles of Programming Languages - Computer Sciencelou/314-f04-slides/topic05_imperativeB.pdfCS 314, LS, BR, LTM: Imperative Programming 11 Heap Storage void *malloc (size_t n)](https://reader031.vdocuments.mx/reader031/viewer/2022040405/5e9c5b939c0d1725fc3aee68/html5/thumbnails/38.jpg)
CS 314, LS, BR, LTM: Imperative Programming 38
Arrays and PointersArrays and Pointers
• An array name is considered to be a pointer to itsfirst element. Thus, given the declarations:
int A[20], *ip;– A is a pointer to A[0]– ip = A; and ip = &A[0]; have the same meaning
• Array subscripting is defined in terms of “pointerarithmetic”– *(A + 3) and A[3] have the same meaning
• Array names are not variables, but constants– A++ and A = ip are illegal
![Page 39: Principles of Programming Languages - Computer Sciencelou/314-f04-slides/topic05_imperativeB.pdfCS 314, LS, BR, LTM: Imperative Programming 11 Heap Storage void *malloc (size_t n)](https://reader031.vdocuments.mx/reader031/viewer/2022040405/5e9c5b939c0d1725fc3aee68/html5/thumbnails/39.jpg)
CS 314, LS, BR, LTM: Imperative Programming 39
Arrays and PointersArrays and Pointers
• Pointer Arithmetic:int j = 5; int *k = &j;(*k+2) means ((*k)+2) : legal R-value, illegal L-value(k+2) : legal R-value, legal (but not necessarily meaningful) L-value*(k+2) : legal R-value, illegal L-value
• General Rule:Given declaration T *ptr;(ptr + k) points to location ptr + k • sizeof(T)
j5
k1024
1024
1032
![Page 40: Principles of Programming Languages - Computer Sciencelou/314-f04-slides/topic05_imperativeB.pdfCS 314, LS, BR, LTM: Imperative Programming 11 Heap Storage void *malloc (size_t n)](https://reader031.vdocuments.mx/reader031/viewer/2022040405/5e9c5b939c0d1725fc3aee68/html5/thumbnails/40.jpg)
CS 314, LS, BR, LTM: Imperative Programming 40
Arrays and PointersArrays and Pointers
• Two ways to process the array A[20]– with subscripts:
int k;for(k=0; k < 20; k++){ A[k] = 0;}
– with pointers:int *ap;for(ap=A; ap < A+20; ap++){ *ap = 0;}
![Page 41: Principles of Programming Languages - Computer Sciencelou/314-f04-slides/topic05_imperativeB.pdfCS 314, LS, BR, LTM: Imperative Programming 11 Heap Storage void *malloc (size_t n)](https://reader031.vdocuments.mx/reader031/viewer/2022040405/5e9c5b939c0d1725fc3aee68/html5/thumbnails/41.jpg)
CS 314, LS, BR, LTM: Imperative Programming 41
Strings and PointersStrings and Pointers
• The library package string.h assumes that a stringis an array of characters terminated by ‘\0’.
• Thus: char name[5] = “Mary”;
• Example: int strlen(char const *str){
int n=0; for( ; *str != ‘\0’; str++) { n+=1;}
return n; }
![Page 42: Principles of Programming Languages - Computer Sciencelou/314-f04-slides/topic05_imperativeB.pdfCS 314, LS, BR, LTM: Imperative Programming 11 Heap Storage void *malloc (size_t n)](https://reader031.vdocuments.mx/reader031/viewer/2022040405/5e9c5b939c0d1725fc3aee68/html5/thumbnails/42.jpg)
CS 314, LS, BR, LTM: Imperative Programming 42
Strings and PointersStrings and Pointers
• Example: char *strcpy(char *dst, char const *src){
char *str = dst; for( ; *src != ‘\0’ ; src++, dst++)
{*dst = *src;} *dst = ‘\0’;
return str; }
• Caution: User must guarantee that dst has beenallocated enough memory to store src
![Page 43: Principles of Programming Languages - Computer Sciencelou/314-f04-slides/topic05_imperativeB.pdfCS 314, LS, BR, LTM: Imperative Programming 11 Heap Storage void *malloc (size_t n)](https://reader031.vdocuments.mx/reader031/viewer/2022040405/5e9c5b939c0d1725fc3aee68/html5/thumbnails/43.jpg)
CS 314, LS, BR, LTM: Imperative Programming 43
Pointers to FunctionsPointers to Functions
• To search a list of integers using “less than”, define:intlessthanints(void *a, void *b){ if ( *(int *)a < *(int *)b ) return 1; else return 0;}
• Then call:Cell *foundit; int k=5;foundit = searchlist(head, &k, lessthanints);
![Page 44: Principles of Programming Languages - Computer Sciencelou/314-f04-slides/topic05_imperativeB.pdfCS 314, LS, BR, LTM: Imperative Programming 11 Heap Storage void *malloc (size_t n)](https://reader031.vdocuments.mx/reader031/viewer/2022040405/5e9c5b939c0d1725fc3aee68/html5/thumbnails/44.jpg)
CS 314, LS, BR, LTM: Imperative Programming 44
Pointers to FunctionsPointers to Functions
• To search a list of characters using “equals”, define:intequalchars(void *a, void *b){ if ( *(char *)a == *(char *)b ) return 1; else return 0;}
• Then call:Cell *foundit; char ch=‘a’;foundit = searchlist(head, &ch, equalchars);