Download Lecture 3: Pointers and Structures in C and C++ and more Lecture notes C programming in PDF only on Docsity!
Programming in C and C++
Lecture 3: Pointers and Structures
Neel Krishnaswami and Alan Mycroft
Pointers
- Computer memory is often abstracted as a sequence of bytes, grouped into words
- Each byte has a unique address or index into this sequence
- The size of a word (and byte!) determines the size of addressable memory in the machine
- A pointer in C is a variable which contains the memory address of another variable (this can, itself, be a pointer)
- Pointers are declared or defined using an asterisk( * ); for example: char *pc; or int **ppi;
- The asterisk binds to the variable name, not the type specifier; for example char *pc,c;
- A pointer does not necessarily take the same amount of storage space as the type it points to
Manipulating pointers
- The value pointed to by a pointer can be retrieved or dereferenced by using the unary * operator; for example: int *p = ... int x = *p;
- The memory address of a variable is returned with the unary ampersand ( & ) operator; for example int *p = &x;
- Dereferenced pointer values can be used in normal expressions; for example: pi += 5; or (pi)++
Example
1 #include <stdio.h> 2 3 int main(void) { 4 int x=1,y=2; 5 int pi; 6 int ppi; 7 8 pi = &x; ppi = π 9 printf("%p, %p, %d=%d=%d\n",ppi,pi,x,pi,ppi); 10 pi = &y; 11 printf("%p, %p, %d=%d=%d\n",ppi,pi,y,pi,*ppi); 12 13 return 0; 14 }
Pointer arithmetic
- Pointer arithmetic can be used to adjust where a pointer points; for example, if pc points to the first element of an array, after executing pc+=3; then pc points to the fourth element
- A pointer can even be dereferenced using array notation; for example pc[2] represents the value of the array element which is two elements beyond the array element currently pointed to by pc
- In summary, for an array c , *(c+i) == c[i] and c+i == &c[i]
- A pointer is a variable, but an array name is not; therefore pc = c and pc++ are valid, but c = pc and c++ are not
Pointer Arithmetic Example
1 #include <stdio.h> 2 3 int main(void) { 4 char str[] = "A string."; 5 char pc = str; 6 7 printf("%c %c %c\n",str[0],pc,pc[3]); 8 pc += 2; 9 printf("%c %c %c\n",*pc, pc[2], pc[5]); 10 11 return 0; 12 }
Example
Compare swp1(a,b) with swp2(&a,&b): 1 void swp1(int x,int y) 2 { 3 int temp = x; 4 x = y; 5 y = temp; 6 }
1 void swp2(int *px,int *py) 2 { 3 int temp = *px; 4 *px = *py; 5 *py = temp; 6 }
Arrays of pointers
- C allows the creation of arrays of pointers; for example int *a[5];
- Arrays of pointers are particularly useful with strings
- An example is C support of command line arguments: int main(int argc, char *argv[]) { ... }
- In this case argv is an array of character pointers, and argc tells the programmer the length of the array
Multi-dimensional arrays
- Multi-dimensional arrays can be declared in C; for example: int i[5][10];
- Values of the array can be accessed using square brackets; for example: i[3][2]
- When passing a two dimensional array to a function, the first dimension is not needed; for example, the following are equivalent: void f(int i[5][10]) { ... } void f(int i[][10]) { ... } void f(int (*i)[10]) { ... }
- In arrays with higher dimensionality, all but the first dimension must be specified
Pointers to functions
- C allows the programmer to use pointers to functions
- This allows functions to be passed as arguments to functions
- For example, we may wish to parameterise a sort algorithm on different comparison operators (e.g. lexicographically or numerically)
- If the sort routine accepts a pointer to a function, the sort routine can call this function when deciding how to order values
Using a Higher-Order Function in C
1 #include <stdio.h> 2 #include "example8.h" 3 4 int main(void) { 5 int a[] = {1,4,3,2,5}; 6 unsigned int len = 5; 7 sort(a,len,inc); //or sort(a,len,&inc); 8 9 int *pa = a; //C 10 printf("["); 11 while (len--) { printf("%d%s", *pa++, len?" ":""); } 12 printf("]\n"); 13 14 return 0; 15 } 15
The void * pointer
- C has a “typeless” or “generic” pointer: void *p
- This can be a pointer to any object (but not legally to a function)
- This can be useful when dealing with dynamic memory
- Enables polymorphic code; for example: sort(void p, const unsigned int len, int (comp)(void *,void *));
- However this is also a big hole in the type system
- Therefore void * pointers should only be used where necessary
Structure definition
- To define an instance of the structure circle we write struct circle c;
- A structure can also be initialised with values: struct circle c = {12, 23, 5}; struct circle d = {.x = 12, .y = 23, .r = 5}; // C
- An automatic, or local, structure variable can be initialised by function call: struct circle c = circle_init();
- A structure can be declared and several instances defined in one go: struct circle {int x; int y; unsigned int r;} a, b;
Member access
- A structure member can be accessed using ’.’ notation structname.member; for example: vect.x
- Comparison (e.g. vect1 > vect2 ) is undefined
- Pointers to structures may be defined; for example: struct circle *pc;
- When using a pointer to a struct, member access can be achieved with the ‘.’ operator, but can look clumsy; for example: (*pc).x
- Equivalently, the ‘->’ operator can be used; for example: pc->x