Introduction to Pointers in C
What are Pointers in C?
- A pointer is a variable that holds the address of another variable.
- A pointer is a derived data type in C. All the computers have addressable memory locations. The value of these variables is stored in these memories only. We can access these values of the variable in 2 ways:
- (i) By using the name of the variable.
- (ii) By using the address of a variable. The use of pointers are made in the second method
- Values stored in pointers are addresses, where data is stored in memory. Example:
int i = 8;
i → name of the variable
8 → value at address
65599 → address in the memory.
How to Use Pointers in C?
- If we declare a variable i of type int, it will store a value.
- int i = 0
- The value of i is 0 now
- However, each variable, apart from value, also has its own address (or the address of the location where the value is saved in memory). The address can be retrieved by putting an ampersand (&) before the name of the variable.
- &i
- If you print the address, it looks like a random numerical value.
Code Example:
The output of this program is -520645328.
Now a pointer does not store a value but it stores the address.
- Variable: A variable is the name of the memory where a value is saved.
- Pointer: A pointer stores the address of the memory location where that value has been stored.
Declaration of a Pointer:
Pointers can be named anything as long as we follow the rules of C language. A pointer declaration can be of the following form.
data_type * pointer_variable_name;
- data_type is the pointer’s base type of C’s variable types and it defines the type of variable a pointer points to.
- The asterisk (*) known as an indirection operator, declares a pointer.
- e.g.:
- int *a; - integer pointer
- char *ch; - character pointer
- float *num; - float pointer.
- So, “a‟, “ch‟ & “num‟ are pointer variables.
- “a” contains the address of an integer variable.
- Similarly “ch‟ &‟num‟ respectively contain the addresses of character type and string type variables.
Initialization of pointer variable
int a;
int *p; //declaration
p=&a; // initialization
If no initial value is given –
NULL can be assigned as follows-
int*p =NULL; or int *p=0
Some Types of Pointers in C
Following are some Types of Pointers provided by C:
- Null Pointer:
- A null pointer can be created by assigning a null value with the declaration of the pointer. This method is used when we don't have any address assigned to the pointer. A null pointer always contains a value 0.
- Code example:
Output:
The value of variable p is: 0
- Void Pointer:
- A void pointer is also known as a generic pointer. It does not have any standard data type. It can be created by using the void keyword.
- Code Example:
Output:
The size of pointer is:4
- Wild pointer:
- A pointer is said to be a wild pointer if it is not being initialised to anything. These types of C pointers are not efficient because they may point to some unknown memory location which may cause problems in our program. And this problem can also lead to the crashing of the program. We should always be careful while working with wild pointers.
- Code Example:
Output:
timeout: the monitored command dumped core
sh: line 1: 95298 Segmentation fault timeout 10s main
- We can also make pointers to the pointers and so on by adding more asterisks in front of variables:
*p;
**p;
***p;
Pointer Arithmetic:
Here we will have a short look at pointer arithmetic:
- Incrementing a pointer:
- Code Example:
OUTPUT:
Address of arr[0] = bf122b10
Value of arr[0] = 1
Address of arr[1] = bf122b14
Value of arr[1] = 10
- Decrementing a pointer:
- Code Example:
OUTPUT:
Address of arr[2] = bf1346b8
Value of arr[2] = 10
Address of arr[1] = bf13464
Value of arr[1] = 1
Pointers and arrays:
- We can use pointers with arrays. For example — We can make a string of text using an array of characters and call this name, setting its value to first and last name. We can access elements of the array using an index (starting with 0 in C). So to get the letter ‘A’ we can output the first element of that array name[0]. We can use pointers for this purpose.
- Code Example:
This produces the output below:
The first letter of name is A
The first letter of name is A
The first letter of surname is S
The first letter of surname is S
Pointers and strings:
Strings in C are arrays of characters. We can specify the number of characters to be used explicitly between the square brackets or define it by the length of the string:
char str[30] = "This is a string";
char str[] = "This is a string";
We can update the values of these strings. Code Example:
char str[30] = "This is a string";
printf("str = %s", str);
strcpy(str, "New string");
printf("\n\rstr = %s", str);
Output:
str = This is a string
str = New string
We can also use pointers with strings:
char *newStr = "New string"
printf("\n\rnewStr = %s", newStr);
We cannot update this string like we did previously. If we declare a string in this way it is stored in read-only memory in most of the compilers and so it cannot be updated. This is useful in creating immutable strings. Memory can also be created that we can access for a string using the memory allocation function. Then the string can be updated.
char *newStr = (char*)malloc(sizeof(char)*4);
newstr = "Ram";
printf("String = %s", newstr);
newstr = "Shyam";
printf("\n\rString = %s", newstr);
Character pointers can also be used with single characters. When they are used with strings they actually point at the first character of a null-terminated string (\0).
Summary of the topic:
C is a compiled language that is closer to some of the lower level features of computers than many other languages. C programs are compiled and run fastly. This can be especially more advantageous when we need to write optimal code for performance or for making data science libraries in other languages (e.g. Python). Pointers are difficult to master initially but it is an especially powerful tool that can be used in a number of different ways including optimising programs to use less memory and to run faster.
Comments
Post a Comment