Pointers are variables that contain the address of some other variable. Pointers are often used in 'C as their usage leads to more efficient and compact code, Use of pointers under different conditions in 'C programs is explained in this chapter.
Pointers are used everywhere in C, so if you want to use the C language fully you have to have a very good understanding of pointers. You must become comfortable using pointers in C. The goal of this section and the next several that follow is to help you build a complete understanding of pointers and how C uses them. For most people it takes a little time and some practice to become fully comfortable with pointers, but once you master them you are a full-fledged C programmer.
C uses pointers in three different ways:
• C uses pointers to create dynamic data structures: data structures built up from blocks of memory allocated from the heap at run-time.
• C uses pointers to handle variable parameters passed to functions.
• Pointers in C provide an alternative way to access information stored in arrays. Pointer techniques are especially valuable when you work with strings. There is an intimate link between arrays and pointers in C.
We will start this discussion with a basic introduction to pointers and the concepts surrounding pointers, and then move on to the three techniques described above.
Why Use Pointers?
Suppose we want to create a text editor - a program that lets you edit normal ASCII text files, like "vi" on UNIX or "Notepad" on Windows. A text editor is a common thing for someone to create because a text editor is probably a programmer's most commonly used piece of software. A programmer puts in his/her thoughts through the text editor and then manipulates them according to requirements. Therefore, many programmers create their own editors and customize them to suit their individual working styles and preferences.
When we begin working on our editor and think about the features we want, one of the first things that come to our mind is the "data structure" for our editor. We need to think about how we will store the document that we are editing in memory so that we can manipulate it in our program. What we need is a way to store the information we are entering in a form that can be manipulated quickly and easily. One way to do that is to organize the data on the basis of lines of characters. Given what we have discussed so far, the only thing we have at our disposal at this point is an array. We can reason that a typical line is 80 characters long, and a typical file is no more than 1,000 lines long. Therefore we declare a two-dimensional array like this:
chardoc[1000][80];
This declaration requests an array of 1,000 eighty-character lines. This array has a total size of 80,000 characters.
Some more requirements to be kept in mind while designing our editor and the data structure used for it are:
1. Some documents are long lists. Every line may be short, but there may be thousands of lines.
2. Some special-purpose text files can have very long lines. For example, a certain data file might have lines containing 542 characters, with each character representing the amino acid pairs in segments of DNA.
3. In most modern editors, we should be able to open multiple files at one time.
Let's say we stipulate that a maximum of 10 open files can be opened at once, a line has a maximum length of 1,000 characters and a file has a maximum size of 50,000 lines. Our declaration now looks like this;
chardoc[50000][1000][10];
These requirements seem reasonable but when we multiply 50,000 by 1,000 by 10 , the array contains 500 million characters. Most computers today do not have the RAM, or even the virtual memory space, to support an array of that size. If users tried to run three or four copies of this program simultaneously on even the largest multi-user system, it would put a severe strain on the facilities.
Even if the computer accepts a request for such a large array, we can see that it is a waste of space. It is not logical to declare a 500 million character array when, in the vast majority of cases, we will run this editor to look at 100 line files that consume at most 4,000 or 5,000 bytes. The problem with an array is the fact that we have to declare it to have its maximum size in every dimension from the beginning. Those maximum sizes often multiply together to form very large numbers. Also, if at some point of time we really need to edit a file with a 2,000 character line in it, we simply can't do it. There is really no way for us to predict and handle the maximum line length of a text file, because, technically, that number is infinite.
Pointers are designed to solve this problem. With pointers, we can create dynamic data structures (this will be discussed in detail later). Instead of declaring the maximum memory consumption while declaring an array, we instead allocate memory from the heap while the program is running. That way we can use the exact amount of memory a document needs, with no wastage. In addition, when we close a document we can return the memory to the heap so that other parts of the program can use it. With pointers, memory can be recycled while the program is running.
The 'address of and the 'indirection' Operators
The declaration statement int alpha = 1; tells the compiler to
Reserve just enough space in memory to hold an integer value Associate the name alpha with this space Store the value 1 there we may represent alpha's location in memory by the following diagram:
addr value name
9364 1 alpha
Assuming that the compiler has selected memory location 9364 to store the value 1, let us look at the following example:
Example:
main()
{
int alpha = 1 ;
printf ("the value %d is stored at address %d\n", alpha, & alpha);
}
Output:
The value 1 is stored at address 9364.
The & symbol is C's address-of operator. The expression &alpha returns the address associated with the variable we've named alpha; in this case it happens to be 9364. If you run this in your machine you may get a different address value printed.
A second symbol used in C's pointer notation is the indirection operator, '*'.
The operand of the indirection operator is the address of a variable or a variable containing the address of another variable and it returns the value stored at that address.
Therefore, * (&alpha) is the value stored at alpha's address, which is alpha itself.
This is illustrated below:
main()
{
int alpha = 1 ;
printf ("The value %d is stored at addr %u\n", alpha, & alpha);
printf("The value %d is stored at addr %u\n", *(&alpha),&alpha); }
Output:
The value 1 is stored at addr 9364 The value 1 is stored at addr 9364
Observe carefully the output of the following program:
main()
{
int alpha =1;
printf("\n Address of alpha = %u, &alpha);
printf("\n The value of alpha = %d, alpha);
printf("\n The value of alpha = %d,*(&alpha);
}
Output: Address of alpha = 9364 The value of alpha = 1 The value of alpha - 1
Note:
The point to be noted is that *(&alpha) is same as printing the value of alpha.
Pointer Expression
Since addresses themselves are values, they can be given names and stored in memory just like any other value. To do this, we have to make a declaration of the form:
int * beta;
This is a pointer declaration. This tells the compiler that beta is a variable, which will be used to store the address of an integer. We can assign to beta the address of alpha using the assignment statement as follows:
beta = α
Now, the pointer variable beta points to the integer variable alpha.
Since beta is also a variable, the compiler allocates space for it in the memory like for any other variable. This is explained in the next figure.
Example:
#include
int main()
{ int i,j;
int *p; /* a pointer to an integer */ p = &i; *P=5;
printf("%d %d %d\n", i, j, *p); return 0; }
The first declaration in this program declares two normal integer variables named i and j. The line int *p declares a pointer named p. This line asks the compiler to declare a variable p that is a pointer to an integer. The * indicates that a pointer is being declared rather than a normal variable. We can create a pointer to anything: a float, a structure, a char, and so on. We only use a * to indicate that we want a pointer rather than a normal variable.
In C, & is called the address operator. The expression &i means "the memory address of the variable i." Thus, the expression p = &i; means "Assign to p the address of i." Once we execute this statement, p "points to" i. Before we do so, p contains a random, unknown address, and its use is likely to cause a segmentation fault or similar program crash.
One good way to visualize what is happening is to draw a picture. After i, j and p are declared, the picture looks like this:
p '* j
O H E
In this drawing, the three variables i, j and p have been declared, but none of the three has been initialized. The two integer variables are therefore drawn as boxes containing question marks - they could contain any value at this point in the program's execution. The pointer is drawn as a circle to distinguish it from a normal variable that holds a value.
After the line p = &l;, p is initialized and it points to i, like this:
p '. *p j
Once p points to i, the memory location i has two names. It is still known as i, but now it is known as *p as well. This is how C talks about the two parts of a pointer variable: p is the location holding the address, while *p is the location
addr value name
9364 1 alpha
9370 9364 beta
To illustrate the above, consider the following program:
main()
{
int alpha;
int *beta;
alpha = 1;
beta = α
printf ("The value %d is stored at address %u\n", alpha, &alpha);
printf ("The value %d is stored at address %u\n", beta, &beta);
printf ("The value %d is stored at address %u", *beta, beta); }
Output:
The value 1 is stored at address 9364. The value 9364 is stored at address 9370. The value 1 is stored at address 9364.
Understanding Pointers
To understand pointers, it is helpful to compare them to normal variables. A "normal variable" is a location in memory that can hold a value. For example, when we declare a variable i as an integer, two bytes of memory are set aside for it. In our program, we refer to that location in memory by the name i. At the machine level that location has a memory address. The two bytes at that address are known to us, the programmer, as i, and the two bytes can hold one integer value.
A pointer is different. A pointer is a variable that points to another variable. This means that a pointer holds the memory address of another variable. Put another way, the pointer does not hold a value in the traditional sense; instead, it holds the address of another variable. A pointer "points to" that other variable by holding a copy of its address.
Because a pointer holds an address rather than a value, it has two parts. The pointer itself holds the address. That address points to a value. There is the pointer and the value pointed to. This fact can be a little confusing until we get comfortable with it, but once we get used to, it becomes extremely powerful. The following example code shows a typical pointer.
pointed to by that address. Therefore *p=5 means that the location pointed to! by p should be set to 5, as shown now:
p I,*p j
5 ?
Because the location *p is also i, i also takes on the value 5. Consequently, j=i; sets j to 5, and the printf statement produces 5 5 5.
The main feature of a pointer is its two-part nature. The pointer itself holds an ■ address. The pointer also points to a value of a specific type - the value at the I address the point holds. The pointer itself, in this case, is p. The value pointed I to is *p.
Even though p can be used like a variable, it should be noted that p is not a I variable name. We have not defined any variable by that name in our program. I More over, '*' is not a valid character in a variable name. '*' in conjunction with I a pointer variable on a pointer constant is an operator called indirection I operator. You should be able to distinguish between indirection operator '*' and I multiplication operator '*'. The indirection operator '*' works in two ways:
When it appears on the right hand side of an assignment operator as in
i = *p;
it works like this. Look into p, get the content there, go to that location and assign the content there to the left hand side.
When it appears on the left hand side of an assignment operator as in
*P = j;
it works like this. Look into the content of p, go to that location and store the value on the right hand side in that location.
Understanding Memory Addresses
The previous discussion becomes a little clearer if we understand how memory addresses work in a computer's hardware.
All computers have memory, also known as RAM or Random Access Memory. For example, your computer might have 16 or 32 or 64 megabytes of RAM installed right now. RAM holds the programs that your computer is currently running along with the data they are currently manipulating (their variables and data structures). Memory can be thought of simply as an array of bytes. In this array, every memory location has its own address--the address of the first byte is 0, followed by 1, 2, 3,.... Memory addresses act just like the indexes of a normal array. The computer can access any address in memory at any time (hence the name Random Access Memory). It can also group bytes together as it needs to form larger variables, arrays, and structures. For
example, a floating-point variable consumes four contiguous bytes in memory. We can make the following global declaration in a program:
float f;
This statement says, "declare a location named f that can hold one floating point value." When the program runs, the computer reserves space for the variable f somewhere in memory. That location has a fixed address in the memory space, assume
While we think of the variable f, the computer thinks of a specific address in memory (for example, 248,440). Therefore, when we write a statement like this:
f = 3.14;
The compiler might translate that into, "load the value 3.14 into memory location 248,440". The computer is always thinking of memory in terms of addresses and values at those addresses.
There are, several interesting side effects to the way the computer treats memory. For example, let's say that we include the following code in one of our programs:
Example:
#include
void main() {
int i, s[4], t[4], u=0;
for (i=0; i<=4; i++) { s[i] = i; t[i] =i; } printf("s:t\n"); for (i=0; i<=4; i++) printf(,,%d:% d \n,,> s[i], t[i]);
printf(“u = %d\n", u);
The output that you see from the program will look like this:
s:t
4:0
1:1
2:2
3:3
4:4
u = 0
In a C program, you can declare variables outside the main() function as shown below.
int i, s[4], t[4], u=0;
main()
{
}
When variables are declared like this outside the main function, memory allocation takes place in the order in which variables are declared. For the variable declaration given above, the memory allocation will explain like this:
When variables are declared inside the main function, as is done in our example program memory allocation takes place in the reverse order in which the variables are declared. For the variable declaration given in the above program memory allocation takes place as explained below.
When the program runs and executes the statements s[i]=i; t[i]=i for i=4, it will try to write 4 in s[4] and t[4].
Since there is no s[4] and t[4] identified at this moment, the data 4 will bel written in the next memory locations after s[3] and t[3]. This 4 will be written in the space referenced by i and the same space can be referenced by s[4], Similarly 4 will be written in the space referenced by s[0] and the same space can be referenced by t[4].
Because C does not perform any range checking when we access an element of an array, it is essential that we, as a programmer, pay careful attention tol array ranges ourselves and keep within the array's appropriate boundaries.! Unintentionally reading or writing outside of array boundaries always leads toT faulty program behavior.
As an example, let us try the following:
Example:
#include
int main()
{ int i;
int *p;
printf("%u %u\n", p, &i);
p = &i;
printf("%u %u\n", p, &i);
return 0;
}
This code tells the compiler to print out the address held in p, along with the address of i. The variable p starts off with NULL value. The address of i is' generally a large value. For example, one possible output could be:
0 2147478276 2147478276 2147478276
which means that the address of i is 2147478276. Once the statement p = &i; has been executed, p contains the address of i. Let us try this as well:
Example:
#include
void main()
{
int *p; /* a pointer to an integer */
printf("%d\n",*p); }
This code tells the compiler to print the value p points to. However, p has n been initialized yet; it contains the address NULL. In most cases a segmentation fault (or some other run-time error) results, this means that we have used a pointer that points to an invalid area of memory. Usually, an
uninitialized pointer or a bad pointer address is the cause of segmentation faults.
Having said all of this, we can now look at pointers in a completely new light. Let us take the following program as an example:
Example:
#include
int main()
{ int i;
int *p; /* a pointer to an integer */ p = &i; *P=5;
printf(,,0/od %d\n", i, *p); return 0; }
Here is what's happening:
four bytes. The location of i has a specific address, in this case 248,440. The pointer p holds that address once you say p = &i;. Therefore *p and i will both have the value 5.
The pointer p literally holds the address of i. When we say in a program:
printf("%d", p);
what comes out is the actual address of the variable i.
Here is one other interesting fact: any number of pointers can point to the same address. For example, you could declare p, q, and r as integer pointers and sa all of them to point to i as shown next:
int i;
int *p, *q, *r;
p = &i;
q = &i; r^p;
Note that in this code, r points to the same thing that p points to, which is i. We can assign pointers to one another, and the address is copied from the right hand side to the left hand side during the assignment. After executing the above code, the following picture shows how things would look:
P
q \ i,*p,*q,*r
r /
The variable i now has four names: i, *p, *q. and *r. There is no limit on the number of pointers that can hold, and therefore point to, the same address.
Some Common Errors
Error #1 - Uninitialized pointers
One of the easiest ways to create a pointer bug is to try to reference the value of a pointer even though the pointer is uninitialized and does not yet point to a valid address. For example:
int *p;
*p = 12;
The pointer p is uninitialized and points to a random location in memory when we declare it. It could be pointing into the system stack, or the global variables, or into the program's code space, or into the operating system. When we say *p=12;, the program will simply try to write a 12 to whatever random location p points to. The program may explode immediately, or may wait half an hour and then explode, or it may subtly corrupt data in another part of our program and we may never realize it. This can make this error very hard to track down. Make sure to initialize all pointers to a valid address before dereferencing them.
Error #2 - Invalid Pointer References
An invalid pointer reference occurs when a pointer's value is referenced even though the pointer doesn't point to a valid block.
One way to create this error is to say p=q;, when q is uninitialized. The pointer p will then become uninitialized as well, and any reference to *p is an invalid pointer reference.
The only way to avoid this bug is make sure that all pointers point somewhere. Invalid pointer references cause a program to crash inexplicably for the same reasons given in Error #1.
Error #3 - Zero Pointer Reference
A zero pointer reference occurs whenever a pointer pointing to zero is used in a statement that attempts to reference a block. For example, if p is a pointer to an integer, the following code is invalid:
p = 0; *p = 12;
There is no block pointed to by p. Therefore, trying to read or write anything from or to that block is an invalid zero pointer reference. There are good, valid reasons to point a pointer to zero, as we will see in later. Dereferencing such a pointer, however, is invalid.
All of these bugs are fatal to a program that contains them. We must watch our code so that these bugs do not occur.
Data Type Of Pointers
To declare a pointer of any type, the declaration statement is:
data__type * variable_name;
Let us look at the following declarations
int *alpha; char *c; float *f;
here alpha, c and f are declared as pointer variables i.e variables capable of holding addresses. Addresses are always going to be whole numbers, so pointers will always contain whole numbers. The declaration float * f does not mean that f is going to contain a floating point value. What it means is, f is
No comments:
Post a Comment