summaryrefslogtreecommitdiff
path: root/reference/C/CONCEPT/pointers.html
blob: 4830b0971f1741422bd8cd8815409045240bbfc6 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
<title>Pointers</title>
<body bgcolor="#ffffcc">
<hr>
<center><h1>Pointers.</h1></center>
<hr>
<p>
Pointers are at the heart of C. When you crack this subject, you have got the worst
of C behind you. Before you tackle pointers though, you should get a grip
on <a href=arrays.html>arrays</a>.<p>
<ul>
<li><a href="#first">First principles.</a>
<li><a href="#def">Definition of a pointer.</a>
<li><a href="string.html">Pointers to strings.</a>
<li><a href="#arrays">Pointers to arrays.</a>
<li><a href="#compare">Char arrays verses char pointers.</a> 
<li><a href="#void">Void pointers.</a>
<li><a href="#ptrs">Pointers to pointers.</a>
<li><a href="#functions">Pointers to functions.</a>
<li><a href=../MISC/linklists.html>Linked lists.</a>
</ul>
<a name=string>
<a name=basic>
<a name=first>
<hr>
<h2>First Principles.</h2>
To understand pointers, it may be worth understanding how normal
variables are stored. If you disagree, <A HREF="#def">Click here</A>
to move on.
<p>
What does the following program realy mean?
<p>
<table border=2 width=100% bgcolor=ivory>
<tr>
<td>
<pre>

        main()
	{
  	    int Length;     
	}      
</pre>
</td>
</tr>
</table>
<p>
In my mind, it means, reserve enough storage to hold an integer and assign the variable 
name 'Length' to it. The data held in this storage is undefined.
Graphically it looks like:
<pre>

      (Address) (Data)
           ---- ----
          | F1 |   <------- Length
          |----|----|
          | F2 |    |       
          |----|----|
          | F3 |    |
          |----|----|
          | F4 |    |
           ---------    

</pre>
To put a known value into 'Length' we code,  
<p>
<table border=2 width=100% bgcolor=ivory>
<tr>
<td>
<pre>

	main()
	{
	    int Length;
  	    Length = 20;
        }
</pre>
</td>
</tr>
</table>
<p>
the deciamal value 20 (Hex 14) is placed into the storage location.
<pre>

      (Address) (Data)
	   ---- ----
          | F1 | 00 <------- Length
          |----|----|
          | F2 | 00 |
          |----|----|
          | F3 | 00 |
          |----|----|
          | F4 | 14 |
           ---------
     
</pre>
Finally, if the program is expanded to become
<p>
<table border=2 width=100% bgcolor=ivory>
<tr>
<td>
<pre>

      main()
      {
          int Length;

          Length = 20;

          <A HREF="../FUNCTIONS/printf.html">printf</a>("Length is %d\n", Length);
          printf("Address of Length is %p\n", &Length);
      }
      
</pre>
</td>
</tr>
</table>
<p>
The output would look something like this .....
<pre>
    
      Length is 20
      Address of Length is 0xF1
      
</pre>      

Please note the '&Length' on the second printf statement. 
The <b>&</b> means <b>address of</b> Length.  
If you are happy with this, you should push onto the pointers below.
<p>
<a name=def>
<hr>
<h2>Pointer definition.</h2> 

<b>A pointer contains an <a href=../glossary.html#address>address</a> that points 

to data.</b>
<p>
An example of code <a href=../glossary.html#definition>defining</a> a pointer could be...
<p>
<table border=2 width=100% bgcolor=ivory>
<tr>
<td>
<pre>

      main()
      {
          int *Width;
      }

</Pre>
</td>
</tr>
</table>
<p>
A graphical representation could be...
<pre>

      (Address) (Data)
           ---- ----
          | F1 |    <------- Width
          |----|----|
          | F2 |    |
          |----|----|
          | F3 |    |
          |----|----|
          | F4 |    |
           ---------
		   
</pre>
So far, this variable looks the same as above,
 the value stored at 'Width' is unknown.
To place a value in 'Width' you could code.		   
<p>
<Table border=2 width=100% bgcolor=ivory>
<tr>
<td>
<pre>

      main()
      {
          int *Width;                                 /* 1 */

          Width = (int *)malloc(sizeof(int));         /* 2 */

          *Width = 34;                                /* 3 */
      }

</pre>
</td>
</tr>
</table>
<pre>

      (Address) (Data)
           ---- ----    
          | F1 | 00 <------- Width   
	  |----|----|               (Data) (Adress)
          | F2 | 00 |                 ---------
	  |----|----|         -------> 00 | D1 |
	  | F3 | 00 |        |       |----|----|
	  |----|----|  *Width|       | 00 | D2 |
	  | F4 | D1 | -------        |----|----|
	   ---------                 | 00 | D3 |
	                             |----|----|
				     | 22 | D4 |
				      ---------
		 
</pre>

Statements 2 and 3 are important here:
<p>
2) The <a href="../FUNCTIONS/malloc.html">malloc</a> function reserves some storage and puts the address of the
storage into Width.
<p>
3) *Width puts a value into the storage pointed to by Width.
<p>

Unlike the 
<a href="#first">Length = 20</a> example above, the storage pointed to by 'Width'
does NOT contain 34 (22 in Hex), it contains the address where the value
34 can be found.
The final program is...
<p>
<table border=2 width=100% bgcolor=ivory>
<tr>
<td>
<pre>

      main()
      {
          int *Width;                               

          Width  = (int *)malloc(sizeof(int));      
	  *Width = 34;

	  printf("  Data stored at *Width is %d\n", *Width); 
	  printf("       Address of Width is %p\n", &Width);
	  printf("Address stored at Width is %p\n",  Width);
      }
				  
</pre>
</tr>
</td>
</table>
<p>
The program would O/P something like.
<p>
<table border=2 width=100% bgcolor=ivory>
<tr>
<td>
<pre>

          Data stored at *Width is 34
	       Address of Width is 0xF1
	Address stored at Width is 0xD1

</pre>
</td>
</td>
</table>
			
<p>
<a name=why>A pointer can point to any data type, ie 
<a href=data_types.html#int>int</a>,
<a href=data_types.html#float>float</a>,
<a href=data_types.html#char>char</a>.
When <a href=../glossary.html#definition>defining</a> a pointer you 
place an <b>*</b> (asterisk) character 
between the data type and the variable name, here are a few examples. 
<p>
<table border=2 width=100% bgcolor=ivory>
<tr><td>
<pre>

	main()
	{
	    int    count;		/* an integer variable              */
	    int   *pcount;		/* a pointer to an integer variable */
	    float  miles;		/* a floating point variable.	    */
	    float *m;			/* a pointer			    */
	    char   ans;			/* character variable		    */ 	
	    char  *charpointer;		/* pointer to a character variable  */
	}

</pre>
</td></tr></table>
<p>


<p>

<a name=arrays>
<hr>
<h2>Pointers to arrays</h2>
When looking at 
<a href=arrays.html>arrays</a> we had a program that accessed data within a 
two dimensional character array. This is what the code looked like.

<pre>
        main()
        {
          char colours[3][6]={"red","green","blue"};
        }
</pre>
The code above has defined an array of 3 elements, each pointing to  6
character strings.
You can also code it like this. Which is actually more descriptive
because it indicates what is actually going on in storage.
<pre>
        main()
        {
          char *colours[]={"red","green","blue"};
        }
</pre>

Graphically it looks like this:
<p>
<table border=2 width=100% bgcolor=ivory>
<tr><td>
<pre>

<font color="gray">

                        
     colours  *colours *(colours+2) **colours
          |         |       |           |
          |         |       |           |
          V         V       V           |     </font>
         ---       -----------      <font color="gray">    |     </font>
        |   |---->|   |   |   |     <font color="gray">    |     </font>
         ---       -----------      <font color="gray">    |     </font>
                    |   |   |       <font color="gray">    V     </font>
                    |   |   |         -----------------------
                     --------------->| r | e | d |   |   |   |
                        |   |         -----------------------
                        |   |      
                        |   |          -----------------------
                         ---|-------->| g | r | e | e | n |   |
                            |          -----------------------
                            |
                            |          -----------------------
                             -------->| b | l | u | e |   |   |
                                       -----------------------
<font color="gray">		            	        A           A
                                        |           |
                                        |           |
                                **(colours+2)   *(*(colours+2)+3)
</font>                                 
</pre>
</td></tr></table>
<p>
<pre>
	printf("%s \n", colours[1]);
	printf("%s \n", *(colours+1))
</pre>
will both return <b>green</b>.
<p>

<a name=compare>
<hr>
<h2>Char Arrays verses Char pointers</h2>

What is the difference
between these two lumps of code?
<p>
<table border=2 width=100% bgcolor=ivory>
<tr><td>
<pre>
	
  main()			
  {			
      char colour[]="red";		
      printf("%s \n",colour);	
  }				

</pre>
</td><td>
<pre>

  main()
  {				
      char *colour="red";
      printf("%s \n",colour);	
  }				

</pre>
</td></tr></table>
<p>
The answer is, NOTHING! They both print the word 
<b>red</b> because in both cases 'printf' is being passed a pointer to a 
string. 
<p>
An <a href=arrays.html>array</a> of 4 bytes is 
reserved and the text 'red' placed
into the storage array. The contents of the array can be chaged later
BUT on the left, the size of the array is fixed.
<p>
Here is a picture of the example on the right. The 'r' of 'red' is stored 
at address 10, the 'e' is at address 11 etc.

<p>
<img src=../../GRAPHICS/ptr.gif>
<p>
At this point it maybe worth looking at  
the <a href=../FUNCTIONS/malloc.html>malloc</a> function.

<p>
<a name=void>
<hr>
<h2>Void Pointers</h2>

There are times when you write a function but do not know the datatype
of the returned value. When this is the case, you can use a void pointer.
<p>

<table border=2 width=100% bgcolor=ivory>
<tr>
<td>
<pre>

  	int func(void *Ptr);

  	main()
  	{
            char *Str = "abc";

            func(Str);
  	}

  	int func(void *Ptr)
  	{
  	    printf("%s\n", Ptr);
  	}
</pre>
</td>
</tr>
</table>
<p>

<b>Please note, you cant do pointer arithmatic on void pointers.</b>
<p>

<a name=ptrs>
<hr>
<h2>Pointers to pointers</h2>

So far we have looked at pointers to data, but there is no reason why
we should not define a pointer to a pointer.  The syntax looks like this.
<p>

<table border=2 width=100% bgcolor=ivory>
<tr>
<td>
<pre>

	main()
	{
	    char **DoublePtr;
	}
</pre>
</td>
</tr>
</table>
<p>

A common use for these is when you want to return a
pointer in a function parameter.
<p>

<table border=2 width=100% bgcolor=ivory>
<tr>
<td>
<pre>
   	#include <stdlib.h>		/* malloc */

	void Func(char **DoublePtr);

	main()
	{
            char *Ptr;

	    Func(&Ptr);
	}

	void Func(char **DoublePtr)
	{
	    *DoublePtr = <a href=../FUNCTIONS/malloc.html>malloc</a>(50);
	}
</pre>
</td>
</tr>
</table>
<p>

<p>
<a name=functions>
<hr>

<h2>Pointers to functions</h2>

Pointers to functions can be used to create 'callback' functions. 
An example of these pointers can be seen in the 
<a href=../FUNCTIONS/qsort.html>qsort</a> function.
<p>
<h3>Examples.</h3>

<img src="../../GRAPHICS/computer.gif">
<a href="../EXAMPLES/funcpt1.c">Simple example passing a function pointer.</a><p>

<img src="../../GRAPHICS/computer.gif">
<a href="../EXAMPLES/funcpt2.c"> Example passing 'int' variables.</a><p>

<img src="../../GRAPHICS/computer.gif">
<a href="../EXAMPLES/funcpt3.c"> Example passing 'char' and 'char *' variables.</a><p>

<hr>
<h2>See Also:</h2>

<img src="../../GRAPHICS/whiteball.gif">
<a href="../SYNTAX/void.html">VOID keyword.</a>
<p>
<img src="../../GRAPHICS/whiteball.gif">
<a href="../SYNTAX/functions.html">function</a> arguments.
<p>
<img src="../../GRAPHICS/whiteball.gif">
<a href="../MISC/linklists.html">linked lists</a>.
<p>
<img src="../../GRAPHICS/whiteball.gif">
<a href="string.html">Strings</a>.
<p>
<img src="../../GRAPHICS/whiteball.gif">
<a href="arrays.html">Arrays.</a>

<hr>
<p>
<center>
<table border=2 width="80%" bgcolor=ivory>
<tr align=center>
<td width=25%>
<a href="../cref.html">Top</a>
</td><td width="25%">
<a href="../master_index.html">Master Index</a>
</td><td width="25%">
<a href="../SYNTAX/keywords.html">Keywords</a>
</td><td width="25%">
<a href="../FUNCTIONS/funcref.htm">Functions</a>
</td>
</tr>
</table>
</center>
<p>
 
<hr>
<address>Martin Leslie
<script language="JavaScript">
<!--  //
document.write(document.lastModified);
// -->
</script>
</address>