Tutorial - Understanding Pointers in C - Part 1
Tutorial
Compiled from multiple sources on the internet. Note that address values will change depending on the programming platform and operating system.
C - Pointers
Pointers in C are easy and fun to learn. Some C programming tasks are performed more easily with pointers, and other tasks, such as dynamic memory allocation, cannot be performed without using pointers. So it becomes necessary to learn pointers to become a perfect C programmer. Let's start learning them in simple and easy steps.
As you know, every variable is a memory location and every memory location has its address defined which can be accessed using ampersand (&) operator, which denotes an address in memory. Consider the following example, which prints the address of the variables defined.
#include <stdio.h>
int main () {
int var1;
char var2[10];
printf("Address of var1 variable: %x\n", &var1 );
printf("Address of var2 variable: %x\n", &var2 );
return 0;
}
When the above code is compiled and executed, it produces the following result −
Address of var1 variable: bff5a400
Address of var2 variable: bff5a3f6
What are Pointers?
A pointer is a variable whose value is the address of another variable, i.e., direct address of the memory location. Like any variable or constant, you must declare a pointer before using it to store any variable address. The general form of a pointer variable declaration is −
type *var-name;
Here, type is the pointer's base type; it must be a valid C data type and var-name is the name of the pointer variable. The asterisk * used to declare a pointer is the same asterisk used for multiplication. However, in this statement the asterisk is being used to designate a variable as a pointer. Take a look at some of the valid pointer declarations −
int *ip; /* pointer to an integer */
double *dp; /* pointer to a double */
float *fp; /* pointer to a float */
char *ch /* pointer to a character */
The actual data type of the value of all pointers, whether integer, float, character, or otherwise, is the same, a long hexadecimal number that represents a memory address. The only difference between pointers of different data types is the data type of the variable or constant that the pointer points to.
Declaring a pointer
Like variables, pointers have to be declared before they can be used in your program. Pointers can be named anything you want as long as they obey C's naming rules. A pointer declaration has the following form.
data_type * pointer_variable_name;
Here,
data_type is the pointer's base type of C's variable types and indicates the type of the variable that the pointer points to.
unary operator (: the same asterisk used for multiplication) which is indirection operator, declares a pointer. It returns the value of the variable located at the address specified by its operand
Some valid pointer declarations
int *ptr_thing; /* pointer to an integer */
int *ptr1,thing; /* ptr1 is a pointer to type integer and thing is an integer variable */
double *ptr2; /* pointer to a double */
float *ptr3; /* pointer to a float */
char *ch1 ; /* pointer to a character */
float *ptr, variable; /*ptr is a pointer to type float and variable is an ordinary float variable */
Initializing a pointer
After declaring a pointer, we initialize it like standard variables with a variable address. If pointers are not uninitialized and used in the program, the results are unpredictable and potentially disastrous.
To get the address of a variable, we use the ampersand (&)operator, placed before the name of a variable whose address we need. Pointer initialization is done with the following syntax.
pointer = &variable;
The following example demonstrates the action of pointers.
#include <stdio.h>
int main () {
int var = 20; /* actual variable declaration */
int *ip; /* pointer variable declaration */
ip = &var; /* store address of var in pointer variable*/
printf("Address of var variable: %x\n", &var );
/* address stored in pointer variable */
printf("Address stored in ip variable: %x\n", ip );
/* access the value using the pointer */
printf("Value of *ip variable: %d\n", *ip );
return 0;
}
When the above code is compiled and executed, it produces the following result −
Address of var variable: bffd8b3c
Address stored in ip variable: bffd8b3c
Value of *ip variable: 20
Some points to note:
- * - Serves 2 purposes: Declaration of a pointer and Returning the value of the referenced variable
- & - Only 1 Purpose - Returns the address of a variable
NULL Pointers
It is always a good practice to assign a NULL value to a pointer variable in case you do not have an exact address to be assigned. This is done at the time of variable declaration. A pointer that is assigned NULL is called a null pointer.
The NULL pointer is a constant with a value of zero defined in several standard libraries. Consider the following program.
#include <stdio.h>
int main () {
int *ptr = NULL;
printf("The value of ptr is : %x\n", ptr );
return 0;
}
When the above code is compiled and executed, it produces the following result.
The value of ptr is 0
In most of the operating systems, programs are not permitted to access memory at address 0 because that memory is reserved by the operating system. However, the memory address 0 has special significance; it signals that the pointer is not intended to point to an accessible memory location. But by convention, if a pointer contains the null (zero) value, it is assumed to point to nothing.
To check for a null pointer, you can use an 'if' statement as follows
if(ptr) /* succeeds if p is not null */
if(!ptr) /* succeeds if p is null */
Void Pointer
In C programming, a void pointer is also called as a generic pointer. It does not have any standard data type. A void pointer is created by using the keyword void. It can be used to store an address of any variable.
Following program illustrates the use of a void pointer:
#include <stdio.h>
int main()
{
void *p = NULL; //void pointer
printf("The size of pointer is:%d\n",sizeof(p));
return 0;
}
Output:
The size of pointer is:8
Wild pointer
A pointer is said to be a wild pointer if it is not being initialized to anything. These types of pointers are not efficient because they may point to some unknown memory location which may cause problems in our program and it may lead to crashing of the program. One should always be careful while working with wild pointers.
Following program illustrates the use of wild pointer:
#include <stdio.h>
int main()
{
int *p; //wild pointer
printf("\n%d",*p);
return 0;
}
Output
timeout: the monitored command dumped core
sh: line 1: 95298 Segmentation fault timeout 10s main
In HPOJ the output will show : Error - RTE
A few more types of pointers in 'c' are as follows. Read up on them to understand them in detail.
- Dangling pointer
- Complex pointer
- Near pointer
- Far pointer
- Huge pointer
More Details about Pointers
Pointers have many but easy concepts and they are very important to C programming. The following important pointer concepts should be clear to any C programmer
- Pointer arithmetic - There are four arithmetic operators that can be used in pointers: ++, --, +, -
- Array of pointers - You can define arrays to hold a number of pointers.
- Pointer to pointer -C allows you to have pointer on a pointer and so on.
- Passing pointers to functions in C- Passing an argument by reference or by address enable the passed argument to be changed in the calling function by the called function.
- Return pointer from functions in C - C allows a function to return a pointer to the local variable, static variable, and dynamically allocated memory as well.
Exercises
Write a C Program using Pointers
1. To create, initialize and use pointers to print the address of a variable.
2. To add two numbers a and b.
3. To swap two numbers a and b.
4. To convert a given lower case character to upper case character.
5. To declare and initialize (to any value you like) a double, an int, and a char variable. Next declare and initialize a pointer to each of the three variables and finally print the address of, and value stored in, and the memory size (in bytes) of each of the six variables. Use the sizeof() operator to determine the memory size allocated for each variable.
Try to do all the previous exercises and those solved in class with pointers as practice. Use the IDE for this.
Comments