Upload
others
View
2
Download
0
Embed Size (px)
Citation preview
Outline Introduction Pointers Function pointers Riddle & End
Introduction to C: Pointers<Pointer>→ <Objects> |<Pointer>
Nils MoschuringPhD Student (LMU)
Nils Moschuring PhD Student (LMU) , Introduction to C: Pointers 1
Outline Introduction Pointers Function pointers Riddle & End
1 Introduction
2 PointersBasicsUseful: Function argumentsUseful: ArraysDouble Pointersvoid Pointers
3 Function pointers
4 Riddle & End
Nils Moschuring PhD Student (LMU) , Introduction to C: Pointers 2
Outline Introduction Pointers Function pointers Riddle & End
Introduction
Pointers are a specific type of variable available in some programminglanguages, most notably C and C++. The history of pointers is comprised ofopposites:
they enable greatness they enable great fubarnessthey promote readability they exist only to brag
they are the best thing about C they are the most evil thing about C
Of course, both sides are totally right. That’s why they are interesting tounderstand.Many ‘modern’ programming languages have abolished them.The PSC makes heavy use of them.
Important term:
ud=undefined behaviour
Nils Moschuring PhD Student (LMU) , Introduction to C: Pointers 4
Outline Introduction Pointers Function pointers Riddle & End
Memory and Values
This is our physical memory. Each memory is referred to by a unique address.
#1 #2 #3 #4 #5 #6 #7 #8Address
Value
After
1 i n t i = 3 ;
we get:
#1 #2 #3 #4 #5 #6 #7 #8Address
Value 3
The address of object i is #2. The OS decides that!
Nils Moschuring PhD Student (LMU) , Introduction to C: Pointers 5
Outline Introduction Pointers Function pointers Riddle & End
So what do pointers do?
Let’s define and initialize a pointer:
1 i n t ∗ i p = NULL ;
Result:
#1 #2 #3 #4 #5 #6 #7 #8Address
Value 3 Null
Now we let it point to i by setting the value of ip to &i :
2 i p = & i ;
The ampersand (&) is called address of or reference operator.
Nils Moschuring PhD Student (LMU) , Introduction to C: Pointers 7
Outline Introduction Pointers Function pointers Riddle & End
So what do pointers do?
Now we get this:
#1 #2 #3 #4 #5 #6 #7 #8Address
Value 3 #2
And the following is true:
1 i == 3 ;2∗ i p == 3;
3 i p == #2 == & i ;4 &i p == #5;
The asterisk (∗) is called value of or dereference operator.
Note: The asterisk in the definition of ip is not an operator, but a part of thevariable type (ip is of type pointer to int) .
Nils Moschuring PhD Student (LMU) , Introduction to C: Pointers 8
Outline Introduction Pointers Function pointers Riddle & End
What’s the use?
Why do we need them?
Call by Reference↔ Call by ValueLess copyingReturn more values
New array manipulation techniques. C Arrays are always pointers!
Messing things up really hard.
What do other languages do?
They all utilize pointers, but you can not directly control them.
Nils Moschuring PhD Student (LMU) , Introduction to C: Pointers 9
Outline Introduction Pointers Function pointers Riddle & End
Function arguments and pointers
Our code:
1 struct b i g S t r u c t {2 i n t s t u f f [ 2 0 0 ] ;3 } ;4 i n t main ( ) {5 struct b i g S t r u c t myBigStruct ;6 func ( myBigStruct ) ;7 return 1;8 }
Now we want to do stuff in this function. One way:
9 i n t func ( struct b i g S t r u c t a ) {10 p r i n t f ( ”%d\n ” , a . s t u f f [ 5 0 ] ) ;11 }
THIS IS BAD!
Nils Moschuring PhD Student (LMU) , Introduction to C: Pointers 10
Outline Introduction Pointers Function pointers Riddle & End
Function arguments and pointers
Better way to do it:
1 i n t func ( struct b i g S t r u c t *a ) {2 p r i n t f ( ”%d\n ” , a−>s t u f f [ 5 0 ] ) ;3 }4 i n t main ( ) {5 struct b i g S t r u c t myBigStruct ;6 func (& myBigStruct ) ;7 return 0;8 }
This won’t copy anything but ONE address (4-8 byte)!
And you can write, not only read, all the values!
Nils Moschuring PhD Student (LMU) , Introduction to C: Pointers 11
Outline Introduction Pointers Function pointers Riddle & End
Pointers to struct
What’s the arrow?
1 p r i n t f ( ”%d\n ” , a−>s t u f f [ 5 0 ] ) ;
It must be equal to:
2 p r i n t f ( ”%d\n ” , ( ∗a ) . s t u f f [ 5 0 ] ) ;
So it’s a shortcut which makes the code much easier to read.
The arrow operator, -> (that’s a minus sign followed immediately by a greaterthan), dereferences a pointer to select a field.
Nils Moschuring PhD Student (LMU) , Introduction to C: Pointers 12
Outline Introduction Pointers Function pointers Riddle & End
Arrays in C and C++
What happens when creating an array?
1 i n t ar ray [ 5 ] ;
It looks strange, but this:
#1 #2 #3 #4 #5 #6 #7 #8Address
Value #3
With the following true:
2 ar ray == #3;3 &ar ray == #3;
The first expression shows the automatic decay mechanism of C:The array automatically decays into the pointer pointing to it when onlyreferenced by its name (in most cases).
How is that an array?!Nils Moschuring PhD Student (LMU) , Introduction to C: Pointers 13
Outline Introduction Pointers Function pointers Riddle & End
Arrays in C and C++
Let’s find out!
You could do, for example:
1 ar ray [ 0 ] = 9 ;
now, in the physical memory, you would like to have:
#1 #2 #3 #4 #5 #6 #7 #8Address
Value #3 9
And this is what you get! So what is this [0] operator doing?
It must be equal to the asterisk ∗!
Nils Moschuring PhD Student (LMU) , Introduction to C: Pointers 14
Outline Introduction Pointers Function pointers Riddle & End
Arrays in C and C++
But what about:
1 ar ray [ 3 ] = 10;
You will get:
#1 #2 #3 #4 #5 #6 #7 #8Address
Value #3 9 10
So the above equals to:
2∗ ( a r ray + 3) = 10;
The jumping increment is determined by the pointer type (no void pointers↔UD!).
The [] is called offset operator.
Note: The brackets in the definition of array are not operators, they are part ofthe type array.Nils Moschuring PhD Student (LMU) , Introduction to C: Pointers 15
Outline Introduction Pointers Function pointers Riddle & End
Summary of Arrays in C and C++
1 i n t ar ray [ 5 ] ;
≈
2 i n t ∗const ar ray = ( i n t ∗ ) mal loc ( sizeof ( ∗ ar ray ) ∗ 5 ) ;
What does this do:
3 char ∗p = NULL ;4 for ( p = ” N i l s ” ; ∗p != ’ \0 ’ ; p++) {5 p r i n t f ( ”%c ” , ∗p ) ;6 }
CORRECT!
Nils Moschuring PhD Student (LMU) , Introduction to C: Pointers 16
Outline Introduction Pointers Function pointers Riddle & End
Constant strings in depth
What is ”Nils ” equal to?
C will create a constant string in a buffer by internally calling something like:
1 const char b u f f e r [ 5 ] ;
But what does this mean?Inserting the approximation given above, it should approximately be:
2 const char ∗const b u f f e r =( char∗ ) mal loc ( sizeof ( ∗ b u f f e r ) ∗ 5 ) ;
After that, C will insert the characters and add a trailing \0.
”Nils ” is a pointer type object with two specialties:
Its value (i.e. the address it points to) can not be written (the second∗const).
3 / ∗ ” N i l s ” =∗ / b u f f e r=& i ; / / Compiler e r r o r
The memory to which it points can not be written (the first const).
4 / ∗ ” N i l s ” [ 1 ] = ∗ / b u f f e r [ 1 ] = ’ o ’ ; / / Compiler / runt ime e r r o r
Nils Moschuring PhD Student (LMU) , Introduction to C: Pointers 17
Outline Introduction Pointers Function pointers Riddle & End
Higher Dimensional Arrays
Think about this statement:
1 i n t array2D [ 1 0 ] [ 1 0 ] ;
According to what we’ve seen so far, the following
2 array2D [ 2 ] [ 3 ] = 4 ;
means:
3∗ ( ∗ ( array2D + 2) + 3) = 4 ;
An array of pointers, pointed to by our array variable.
Nils Moschuring PhD Student (LMU) , Introduction to C: Pointers 18
Outline Introduction Pointers Function pointers Riddle & End
Obvious follow-up: Pointers to Pointers
We declare and assign a double pointer:
1 i n t ∗∗ i pp = &i p ;
Now we’ll get this:
#1 #2 #3 #4 #5 #6 #7 #8Address
Value 3 #2 #5
If the address of ipp is #7. Things that are true in this case:
2 i == ∗ i p == ∗∗ i pp == 3;3∗ ipp == i p == & i == #2;
4 i pp == &i p == #5;5 &ipp == #7;
Nils Moschuring PhD Student (LMU) , Introduction to C: Pointers 19
Outline Introduction Pointers Function pointers Riddle & End
What’s the use of this mess?(except multidimensional arrays)
You can thus change where the pointers are pointing to!
1 i n t j ;2∗ ipp = & j ;
Now, if the address of j is #4, you’ll get this:
#1 #2 #3 #4 #5 #6 #7 #8Address
Value 3 #4 #5
ippipjiVariable
This enables you to change the targets of pointers via functions.In certain situations this can make the code far better.
(and really difficult to understand)
Nils Moschuring PhD Student (LMU) , Introduction to C: Pointers 20
Outline Introduction Pointers Function pointers Riddle & End
Traps and problems
Suppose you need a function which creates a list of objects for you:
1 struct my st ruc t ∗ l i s t ;2 genera te my s t ruc ts (& l i s t ) ;
Double pointers are needed! Lets look at this function:
3 void genera te my s t ruc ts ( struct my st ruc t ∗∗ l i s t ) {4
∗ l i s t = mal loc (5 ∗ sizeof ( ∗∗ l i s t ) ) ;
How can write a data field of the second object?
5 ( ∗ l i s t ) [ 2 ] . a t t r = 5 ;6 }
wrong (operator precedence):
7 l i s t [2]−> a t t r = 5 ;8 * l i s t [ 2 ] . a t t r = 5 ;
First one will not produce a compilation error!In most cases not even a runtime error!
Nils Moschuring PhD Student (LMU) , Introduction to C: Pointers 21
Outline Introduction Pointers Function pointers Riddle & End
Solution to this
Avoid double pointers.Seriously.How to do it without them?
Use more levels of structures
No double pointers needed
Extra level of names which always helps to clarify the code
1 struct m y l i s t s t r u c t {2 struct my st ruc t ∗ l i s t ;3 } ;4 void generate ( struct m y l i s t s t r u c t ∗ l i s t s t r u c t ) {5 l i s t s t r u c t −> l i s t =6 malloc (5 ∗ sizeof ( ∗ l i s t s t r u c t −> l i s t ) ) ;7 l i s t s t r u c t −> l i s t [ 2 ] . a t t r = 5 ;8 }9 struct m y l i s t s t r u c t l i s t s t r u c t ;
10 generate (& l i s t s t r u c t ) ;
Nils Moschuring PhD Student (LMU) , Introduction to C: Pointers 22
Outline Introduction Pointers Function pointers Riddle & End
void Pointers
It’s a special type of Pointer
Pointers pointing to a value that has no type
They can point to any datataype (and even functions)
They are essentially just bare pointers, just addresses
They can’t be directly dereferenced, as the result wouldn’t have a type
You need to always typecast them to a different pointer type beforedereferencing. Example:
1 i n t main ( ) {2 void ∗vp = mal loc ( sizeof ( i n t ) ) ;3 p r i n t f ( ”%d\n ” , ∗ ( ( i n t ∗ ) vp ) ) ;4 f r ee ( vp ) ;5 return 0;6 }
Incrementing and decrementing (or using the offset operator) will use 1byte as the step size (even though sizeof(void) does not work).
Nils Moschuring PhD Student (LMU) , Introduction to C: Pointers 23
Outline Introduction Pointers Function pointers Riddle & End
void Pointers, two examples
The malloc function
Definition:
1 void ∗malloc ( s i z e t s ize ) ;
→ The OS never knows about the ‘type’ of your memory
But it does remember its length.
void function arguments
2 void increase ( void∗ data , i n t psize ) {3 i f ( ps ize == sizeof ( char ) )4 { char∗ pchar ; pchar = ( char∗ ) data ; ++(∗pchar ) ; }5 else i f ( ps ize == sizeof ( i n t ) )6 { i n t ∗ p i n t ; p i n t = ( i n t ∗ ) data ; ++(∗ p i n t ) ; }7 }
Nils Moschuring PhD Student (LMU) , Introduction to C: Pointers 24
Outline Introduction Pointers Function pointers Riddle & End
Function pointers
You can create pointers to functions.This enables, among other things, Late-Binding (PSC!).
Declaration:
1 i n t ( ∗ fp ) ( int , i n t ) ;
This is a function pointer to a function of the following type:
return value: inttwo int arguments
↔ Functions with prototype: int function( int , int );
Assignement & Function call:
2 fp = &f u n c t i o n ;3 ( ∗ fp ) ( 1 , 1 ) ; / / Employing the ( ) f u n c t i o n c a l l opera tor
The Ampersand can also be left out, since function pointers are also subject toautomatic decay.Nils Moschuring PhD Student (LMU) , Introduction to C: Pointers 26
Outline Introduction Pointers Function pointers Riddle & End
Function pointers, example
Obligatory senseless example:
1 i n t subs t r ac t i on ( i n t i , i n t j ){ return i − j ;}2 i n t plus ( i n t i , i n t j ){ return i + j ;}3 i n t opera t ion ( i n t i , i n t j , i n t ( ∗ fp ) ( int , i n t ) ) {4 return ( ∗ fp ) ( i , j ) ;5 }6 i n t main ( ) {7 i n t ( ∗minus ) ( int , i n t ) = &subs t r ac t i on ;8 p r i n t f ( ”%d\n ” , opera t ion (1 , 1 , minus ) ) ;9 p r i n t f ( ”%d\n ” , opera t ion (1 , 1 , &plus ) ) ;
10 return 0;11 }
Returns:
11 012 2
Nils Moschuring PhD Student (LMU) , Introduction to C: Pointers 27
Outline Introduction Pointers Function pointers Riddle & End
Riddle & End
1 i n t number ( i n t i ){ return i ∗ 3;}2 i n t main ( i n t arg ) {3 s t a t i c i n t count = 0 ;4 i n t ( ∗ f pa r ray [ 1 0 ] ) ( i n t ) ;5 for ( i n t i =0; i <10; i ++) fpa r ray [ i ] = &number ;6
∗ ( f pa r ray + 4) = &main ;7 for ( i n t i = ( ∗ f pa r ray[−−arg ] ) ( arg ) ; i <10; i ++) {8 p r i n t f ( ”%d ” , ( ∗∗ ( f pa r ray + i ) ) ( i ) ) ;9 count ++; i f ( count>5) break ;
10 }11 return 666;12 }
13 036927666
Take-Home-Message
Now you’re thinking in pointers...
Nils Moschuring PhD Student (LMU) , Introduction to C: Pointers 29