POINTERS


POINTERS 
 
Pointer are a fundamental part of C. 
If you cannot use pointers properly then you have basically lost all the power 
and flexibility that C allows. 

The secret to C is in its use of pointers. 

C uses pointers a lot. Why?: 

It is the only way to express some computations. 

It produces compact and efficient code. 

It provides a very powerful tool. 

C uses pointers explicitly with: 


Arrays, 

Structures, 

Functions. 

NOTE:
 

Pointers are perhaps the most difficult part of C to understand. C's 

implementation is slightly different DIFFERENT from other languages. 

WHAT IS A POINTER? 


A pointer is a variable which contains the address in memory of another 

variable. We can have a pointer to any variable type. 

The unary or monadic operator & gives the ``address of a variable''. 

The indirection or dereference operator * gives the ``contents of an object 

pointed to by a pointer''. 

To declare a pointer to a variable do: 

   INT *POINTER;



NOTE: 


WE MUST ASSOCIATE A POINTER TO A PARTICULAR TYPE: YOU CAN'T ASSIGN THE ADDRESS 

OF A SHORT INT TO A LONG INT, FOR INSTANCE.

Consider the effect of the following code: 





INT X = 1, Y = 2;
INT *IP;
IP = &X;




Y = *IP;
X = IP;
*IP = 3;


It is worth considering what is going on at the machine level in memory to 

fully understand how pointer work.

Assume for the sake of this discussion that variable x resides at memory 

location 100, y at 200 and ip at 1000. Note A pointer is a variable and thus 

its values need to be stored somewhere. It is the nature of the pointers value 

that is new. 


Pointer, Variables and Memory Now the assignments x = 1 and y = 2 obviously 

load these values into the variables. ip is declared to be a pointer to an 
integer and is assigned to the address of x (&x). So ip gets loaded with the 
value 100. 

Next y gets assigned to the contents of ip. In this example ip currently 

points to memory location 100 -- the location of x. So y gets assigned to the 

values of x -- which is 1. 


We have already seen that C is not too fussy about assigning values of 

different type. Thus it is perfectly legal (although not all that common) to 
assign the current value of ip to x. The value of ip at this instant is 100


Finally we can assign a value to the contents of a pointer (*ip). 



IMPORTANT:


When a pointer is declared it does not point anywhere. You must set it to 


point somewhere before you use it. 


So ... 


INT *IP;

*IP = 100;


will generate an error (program crash!!). 

The correct use is: 


INT *IP;
INT X;

IP = &X;
*IP = 100;


We can do integer arithmetic on a pointer:




FLOAT *FLP, *FLQ;

*FLP = *FLP + 10;

++*FLP;

(*FLP)++;

FLQ = FLP;




NOTE:
 

A POINTER TO ANY VARIABLE TYPE IS AN ADDRESS IN MEMORY -- WHICH IS AN INTEGER 

ADDRESS. A POINTER IS DEFINITELY NOT AN INTEGER.

The reason we associate a pointer to a data type is so that it knows how many 
bytes the data is stored in. When we increment a pointer we increase the pointer by one ``block'' memory. 

So for a character pointer ++ch_ptr adds 1 byte to the address.

For an integer or float ++ip or ++flp adds 4 bytes to the address. 

Consider a float variable (fl) and a pointer to a float (flp) as shown in Fig 














Pointer Arithmetic Assume that flp points to fl then if we increment the 
pointer ( ++flp) it moves to the position shown 4 bytes on. If on the other 
hand we added 2 to the pointer then it moves 2 float positions i.e 8 bytes as 


shown in the Figure. 


POINTER AND FUNCTIONS 


Let us now examine the close relationship between pointers and C's other major 
parts. We will start with functions. 

When C passes arguments to functions it passes them by valu

There are many cases when we may want to alter a passed argument in the 
function and receive the new value back once to function has finished.

Other languages do this (e.g. var parameters in PASCAL). C uses pointers explicitly 
to do this. Other languages mask the fact that pointers also underpin the 
implementation of this. 

The best way to study this is to look at an example where we must be able to 
receive changed parameters. 

Let us try and write a function to swap variables around? 

The usual function call: 


swap(a, b)   WON'T WORK. 

Pointers provide the solution: Pass the address of the variables to the 
functions and access address of function. 

Thus our function call in our program would look like this: 

SWAP(&A, &B)

The Code to swap is fairly straightforward: 


VOID SWAP(INT *PX, INT *PY)

{ INT TEMP;

TEMP = *PX;
/* CONTENTS OF POINTER */

*PX = *PY;
*PY = TEMP;
}



We can return pointer from functions. A common example is when passing back 

structures. e.g.: 

TYPEDEF STRUCT {FLOAT X,Y,Z;} COORD;
MAIN()




{  COORD P1, *COORD_FN();
/* DECLARE FN TO RETURN PTR OF
COORD TYPE */
....
P1 = *COORD_FN(...);
/* ASSIGN CONTENTS OF ADDRESS RETURNED */
....
}

COORD *COORD_FN(...)
{  COORD P;
.....
P = ....;
/* ASSIGN STRUCTURE VALUES */

RETURN &P;
/* RETURN ADDRESS OF P */
}


Here we return a pointer whose contents are immediately unwrapped into a 
variable. We must do this straight away as the variable we pointed to was
local to a function that has now finished. 

This means that the address space is free and can be overwritten. It will not 
have been overwritten straight after the function ha squit though so this is 
perfectly safe. 

POINTERS AND ARRAYS 

Pointers and arrays are very closely linked in C. 


Hint:
 

think of array elements arranged in consecutive memory locations.

Consider the following: 

INT A[10], X;
INT *PA;
PA = &A[0];  /* PA POINTER TO ADDRESS OF A[0] */
X = *PA;
/* X = CONTENTS OF PA (A[0] IN THIS CASE) */



?




Arrays and Pointers 

To get somewhere in the array using a pointer we could do: 

PA + I ?A[I]

WARNING: 


THERE IS NO BOUND CHECKING OF ARRAYS AND POINTERS SO YOU CAN EASILY GO BEYOND 
ARRAY MEMORY AND OVERWRITE OTHER THINGS. 

C however is much more subtle in its link between arrays and pointers. 

For example we can just type 

PA = A;

instead of 

PA = &A[0]

and 

A[I] CAN BE WRITTEN AS *(A + I). 

I.E. &A[I] ?A + I.

We also express pointer addressing like this: 

PA[I] ?*(PA + I).

However pointers and arrays are different: 


A pointer is a variable. We can do 

pa = a and pa++. 

An Array is not a variable. a = pa and a++ ARE ILLEGAL. 

This stuff is very important. Make sure you understand it. We will see a lot 
more of this. 

We can now understand how arrays are passed to functions. 

When an array is passed to a function what is actually passed is its initial 
elements location in memory. 

So: 

STRLEN(S) ?STRLEN(&S[0])

This is why we declare the function: 

INT STRLEN(CHAR S[]);

An equivalent declaration is : int strlen(char *s); 

since char s[] ?char *s. 

NOTE:





strlen() is a standard library function that returns the length of a string. 




Let's look at how we may write a function: 





INT STRLEN(CHAR *S)
{ CHAR *P = S;




WHILE (*P != `?);
P++;
RETURN P-S;
}
NOW LETS WRITE A FUNCTION TO COPY A STRING TO ANOTHER STRING. STRCPY() IS A 
STANDARD LIBRARY FUNCTION THAT DOES THIS. 


VOID STRCPY(CHAR *S, CHAR *T)
{  WHILE ( (*S++ = *T++) != `?);}


This uses pointers and assignment by value. 

Very Neat!! 

NOTE: 


Uses of Null statements with while. 


ARRAYS OF POINTERS 

We can have arrays of pointers since pointers are variables. 

Example use: 

Sort lines of text of different length. 

NOTE:


Text can't be moved or compared in a single operation. 

Arrays of Pointers are a data representation that will cope efficiently and 
conveniently with variable length text lines. 

How can we do this?: 


Store lines end-to-end in one big char array .?n will delimit lines. 

Store pointers in a different array where each pointer points to 1st char of 
each new line. 

Compare two lines using strcmp() standard library function. 

If 2 lines are out of order -- swap pointer in pointer array (not text). 




Arrays of Pointers (String Sorting Example) 

This eliminates: 


complicated storage management. 

high overheads of moving lines. 

MULTIDIMENSIONAL ARRAYS AND POINTERS 


We should think of multidimensional arrays in a different way in C: 

A 2D array is really a 1D array, each of whose elements is itself an array 

Hence 

  a[n][m] notation. 


Array elements are stored row by row. 

When we pass a 2D array to a function we must specify the number of columns -- 
the number of rows is irrelevant. 

The reason for this is pointers again. C needs to know how many columns in 
order that it can jump from row to row in memory.

Considerint a[5][35] to be passed in a function:

We can do: 
F(INT A[][35]) {.....}
or even: 
F(INT (*A)[35]) {.....}


We need parenthesis (*a) since [] have a higher precedence than * 


So:

int (*a)[35]; declares a pointer to an array of 35 ints. 
int *a[35]; declares an array of 35 pointers to ints. 


Now lets look at the (subtle) difference between pointers and arrays. Strings 
are a common application of this. 

CONSIDER: 

CHAR *NAME[10];
CHAR ANAME[10][20];

We can legally do name[3][4] and Aname[3][4] in C. 

However 

Aname is a true 200 element 2D char array. 

access elements via 

20*row + col + base_address 
in memory. 

name has 10 pointer elements. 

NOTE:

If each pointer in name is set to point to a 20 element array then and only 
then will 200 chars be set aside (+ 10 elements).

The advantage of the latter is that each pointer can point to arrays be of 
different length. 

Consider: 

CHAR *NAME[] = { ``NO MONTH'', ``JAN'',
``FEB'', ... };
CHAR ANAME[][15] = { ``NO MONTH'', ``JAN'',
``FEB'', ... };    






2D Arrays and Arrays of Pointers 

STATIC INITIALISATION OF POINTER ARRAYS 


Initialisation of arrays of pointers is an ideal application for an internal 
static array. 


SOME_FN()
{ STATIC CHAR *MONTHS = { ``NO MONTH'',
``JAN'', ``FEB'',
...};

}

static reserves a private permanent bit of memory. 

POINTERS AND STRUCTURES 


These are fairly straight forward and are easily defined. Consider the 
following: 

   STRUCT COORD {FLOAT X,Y,Z;} PT;
STRUCT COORD *PT_PTR;


PT_PTR = &PT; /* ASSIGNS POINTER TO PT */
the ?operator lets us access a member of the structure pointed to by a 
pointer.i.e.: 
pt_ptr?x = 1.0; 
pt_ptr?y = pt_ptr?y - 3.0; 


Example: Linked Lists 

TYPEDEF STRUCT {  INT VALUE;
ELEMENT *NEXT;
} ELEMENT;

ELEMENT N1, N2;

N1.NEXT = &N2;




Linking Two Nodes NOTE: We can only declare next as a pointer to ELEMENT. We 
cannot have a element of the variable type as this would set up a recursive 
definition which is NOT ALLOWED. We are allowed to set a pointer reference 
since 4 bytes are set aside for any pointer. 

The above code links a node n1 to n2 we will look at this matter further in
the next Chapter. 

COMMON POINTER PITFALLS 


Here we will highlight two common mistakes made with pointers. 

NOT ASSIGNING A POINTER TO MEMORY ADDRESS BEFORE USING IT 

INT *X;
*X = 100;

WE NEED A PHYSICAL LOCATION SAY: INT Y;

X = &Y;
*X = 100;

This may be hard to spot. NO COMPILER ERROR. Also x could some random address 
at initialisation. 

ILLEGAL INDIRECTION 


Suppose we have a function malloc() which tries to allocate memory dynamically 
(at run time) and returns a pointer to block of memory requested if successful 
or a NULL pointer otherwise. 

char *malloc() -- a standard library function (see later). 

Let us have a pointer: char *p; 

Consider: 

*p = (char *) malloc(100);    /* request 100 bytes of memory */ 

*P = `Y';

There is mistake above. What is it? 

No * in 

*P = (CHAR *) MALLOC(100);

Malloc returns a pointer. Also p does not point to any address. 

The correct code should be: 

P = (CHAR *) MALLOC(100);

If code rectified one problem is if no memory is available and p is NULL. 

Therefore we can't do: 

*p = `y';. 

No comments:

Post a Comment