Sei sulla pagina 1di 35

Lecture-7

Pointers
We’ll Learn Today
• Introduction
• Pointer Variable Definition & Initialization
• Pointer Operators
• Calling Function by Reference
• Using const Qualifier in Pointers
• Pointers & Arrays
• Pointers & 2-Dimentional Arrays
• Excercise
Introduction
• 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.
Pointer Variable Definitions and
Initialization
• Pointer variables
– Contain memory addresses as their
values
– Normal variables contain a specific
value (direct reference)
count
7
– Pointers contain address of a variable
that has a specific value (indirect
reference) countPtr count
7

– Indirection – referencing a pointer value


Pointer Variable Definitions and
Initialization
• Pointer definitions
– * used with pointer variables
int *myPtr;

– Defines a pointer to an int (pointer of type int


*)
– Multiple pointers require using a * before each
variable definition
int *myPtr1, *myPtr2;

– Can define pointers to any data type


– Initialize pointers to 0, NULL, or an address
• 0 or NULL – points to nothing (NULL preferred)
Pointer Operators
• & (address operator)
– Returns address of operand
int y = 5;
int *yPtr;
yPtr = &y; /* yPtr gets address of y */
yPtr “points to” y

y yptr y
5 500000 600000 600000 5
yPtr

Address of y
is value of
yptr
Important Concepts
Important Concepts(cont’d)

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;
Important Concepts(cont’d)

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.
Important Concepts(cont’d)

• The reason we associate a pointer to a data type is so that it can show


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. below.

• Above 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.
Simple Example

void main(void)
{
int a,b;
int *pa, *pb;
a=5; b=10;
pa=&a; pb=&b;

*pa = *pa +10;


*pb = *pb +10;

printf(“ %d “, a);
printf(“\n %d “,b);
}
Another Example
void main(void)
{
int I, *p1, **p2;
i=5;
p1 = &I;
p2 = &p1;
pirntf(“ %d “, **p2 );
printf(“ %d “, * p1);
}
What will be the output??????
Calling Functions by Reference
• Call by reference with pointer arguments
– Pass address of argument using & operator
– Allows you to change actual location in
memory
– Arrays are not passed with & because the array
name is already a pointer
• * operator
– Used as alias/nickname for variable inside of
function
void double( int *number )
{
*number = 2 * ( *number );
}
– *number used as nickname for the variable
passed
Conceptual Example
(Call-by-Value)
int main() number int cubeByValue( int n )
{ {
int number = 5; 5 return n * n * n;
}
number=cubeByValue(number); n
}
undefined

After cubeByValue receives the call:


int main() number int cubeByValue( int n )
{ {
int number = 5; 5 return n * n * n;
}
number = cubeByValue( number ); n
} 5

After cubeByValue cubes parameter n and before cubeByValue returns to main :

int main() number int cubeByValue( int n )


{ { 125
int number = 5; 5 return n * n * n;
}
number = cubeByValue( number ); n
}
5
Conceptual Example
(Call-by-Value)

After cubeByValue returns to main and before assigning the result to number:
int main() number int cubeByValue( int n )
{ {
int number = 5; 5 return n * n * n;
125 }
number = cubeByValue( number ); n
}
undefined

After main completes the assignment to number:


int main() number int cubeByValue( int n )
{ {
int number = 5; 125 return n * n * n;
125 125 }
number = cubeByValue( number ); n
}
undefined
Conceptual Example
(Call-by-Reference)
Before main calls cubeByReference :

int main() number void cubeByReference( int *nPtr )


{ {
5
int number = 5; *nPtr = *nPtr * *nPtr * *nPtr;
}
cubeByReference( &number ); nPtr
} undefined

After cubeByReference receives the call and before *nPtr is cubed:


int main() number void cubeByReference( int *nPtr )
{ {
5
int number = 5; *nPtr = *nPtr * *nPtr * *nPtr;
}
cubeByReference( &number ); nPtr
} call establishes this pointer

After *nPtr is cubed and before program control returns to main :


int main() number void cubeByReference( int *nPtr )
{ { 125
125
int number = 5; *nPtr = *nPtr * *nPtr * *nPtr;
}
cubeByReference( &number ); nPtr
called function modifies
} caller’s variable
Using the const Qualifier with
Pointers
• const qualifier
– Variable cannot be changed
– Use const if function does not need to change a variable
– Attempting to change a const variable produces an error
• const pointers
– Point to a constant memory location
– Must be initialized when defined
– int *const myPtr = &x;
• Type int *const – constant pointer to an int
– const int *myPtr = &x;
• Regular pointer to a const int
– const int *const Ptr = &x;
• const pointer to a const int
• x can be changed, but not *Ptr
1 /* Fig. 7.10: fig07_10.c
2 Converting lowercase letters to uppercase letters
3 using a non-constant pointer to non-constant data */
4
5 #include <stdio.h>
6 #include <ctype.h>
7
8 void convertToUppercase( char *sPtr ); /* prototype */
9
10 int main()
11 {
12 char string[] = "characters and $32.98"; /* initialize char array */
13
14 printf( "The string before conversion is: %s", string );
15 convertToUppercase( string );
16 printf( "\nThe string after conversion is: %s\n", string );
17
18 return 0; /* indicates successful termination */
19
20 } /* end main */
21
22 /* convert string to uppercase letters */
23 void convertToUppercase( char *sPtr )
24 {
25 while ( *sPtr != '\0' ) { /* current character is not '\0' */
26
27 if ( islower( *sPtr ) ) { /* if character is lowercase, */
28 *sPtr = toupper( *sPtr ); /* convert to uppercase */
29 } /* end if */
30
31 ++sPtr; /* move sPtr to the next character */
32 } /* end while */
33
34 } /* end function convertToUppercase */
The string before conversion is: characters and $32.98
The string after conversion is: CHARACTERS AND $32.98
1 /* Fig. 7.11: fig07_11.c
2 Printing a string one character at a time using
3 a non-constant pointer to constant data */
4
5 #include <stdio.h>
6
7 void printCharacters( const char *sPtr );
8
9 int main()
10 {
11 /* initialize char array */
12 char string[] = "print characters of a string";
13
14 printf( "The string is:\n" );
15 printCharacters( string );
16 printf( "\n" );
17
18 return 0; /* indicates successful termination */
19
20 } /* end main */
21
22 /* sPtr cannot modify the character to which it points,
23 i.e., sPtr is a "read-only" pointer */
24 void printCharacters( const char *sPtr )
25 {
26 /* loop through entire string */
27 for ( ; *sPtr != '\0'; sPtr++ ) { /* no initialization */
28 printf( "%c", *sPtr );
29 } /* end for */
30
31 } /* end function printCharacters */
The string is:
print characters of a string
1 /* Fig. 7.12: fig07_12.c
2 Attempting to modify data through a
3 non-constant pointer to constant data. */
4 #include <stdio.h>
5
6 void f( const int *xPtr ); /* prototype */
7
8 int main()
9 {
10 int y; /* define y */
11
12 f( &y ); /* f attempts illegal modification */
13
14 return 0; /* indicates successful termination */
15
16 } /* end main */
17
18 /* xPtr cannot be used to modify the
19 value of the variable to which it points */
20 void f( const int *xPtr )
21 {
22 *xPtr = 100; /* error: cannot modify a const object */
23 } /* end function f */
1 /* Fig. 7.13: fig07_13.c
2 Attempting to modify a constant pointer to non-constant data */
3 #include <stdio.h>
4
5 int main()
6 {
7 int x; /* define x */
Changing *ptr is allowed – x is
8 int y; /* define y */ not a constant.
9
10 /* ptr is a constant pointer to an integer that can be modified
11 through ptr, but ptr always points to the same memory location */
12 int * const ptr = &x;
13
14 *ptr = 7; /* allowed: *ptr is not const */
15 ptr = &y; /* error: ptr is const; cannot assign new address */
16
17 return 0; /* indicates successful termination */
18 Changing ptr is an error –
19 } /* end main */ ptr is a constant pointer.
1 /* Fig. 7.14: fig07_14.c
2 Attempting to modify a constant pointer to constant data. */
3 #include <stdio.h>
4
5 int main()
6 {
7 int x = 5; /* initialize x */
8 int y; /* define y */
9
10 /* ptr is a constant pointer to a constant integer. ptr always
11 points to the same location; the integer at that location
12 cannot be modified */
13 const int *const ptr = &x;
14
15 printf( "%d\n", *ptr );
16
17 *ptr = 7; /* error: *ptr is const; cannot assign new value */
18 ptr = &y; /* error: ptr is const; cannot assign new address */
19
20 return 0; /* indicates successful termination */
21
22 } /* end main */
Pointers and Arrays
• Pointers and arrays are very closely linked in C.
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) */

• To get somewhere in the array Fig. 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.
Pointers and Arrays(cont’d)
• 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 can also express pointer addressing like this:
pa[i] = *(pa + i).
Differences between Pointers & Array
• 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.
Simple Example
void main(void)
{
int num[5]={1,2,3,4,5};
int i, *ptr;
ptr = num;
for( i = 0; i<5; i++)
printf(“ %d “, *(ptr++));
}
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
• 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 (Fig.).
\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

This eliminates:
• complicated storage management.
• high overheads of moving lines.
Arrays of Pointers (String Sorting
Example)

void main(void)
{
char *p[5] = {“Rashid”, “Sajid”, “Ali”, Zahid”, “Babar” };
char * tmp; int I, j;
for( i = 0; i<5; i++)
for( j= i+1; j<4; j++ )
{ if( strcmp ( p[ i ], p[ j ]) > 0 )
{ tmp = (char * ) p[ i ] );
p[ i ] = p[ j ];
p[ j ] = tmp;
}
}
for( i = 0; i<5; i++)
puts( p[ i ] );
}
Pointers & 2-Dimentional Array
Example:
main()
{
int a[2][2] = { {3,4}, {5,6} };
int i, j;
for( i = 0; i<2; i++)
for( j=0; j<2; j++)
printf( “%d “, *( *( a + i ) + j ) );
getch();
}
Exercise
• Write a C program to read through an
array of any type using pointers.
Write a C program to scan through
this array to find a particular value.
• Compare two strings for equality. If
they are equal, zero is returned,
otherwise the difference in value
between the first two non-matching
characters.
End of Lecture-7
Any Questions?????

Potrebbero piacerti anche