Page 69 - DCAP201_FUNDAMENTALS_OF_DATA_STRUCTURES
P. 69
Fundamentals of Data Structures
Notes 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.
Example:
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 has quit though so this is perfectly safe.
5.1.2 Pointers and Arrays
Pointers and arrays are very closely linked in C.
Consider of array elements arranged in consecutive memory locations.
62 LOVELY PROFESSIONAL UNIVERSITY