0% found this document useful (0 votes)
86 views13 pages

Pointeri

Download as pdf or txt
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 13

Pointers in C Programming with examples

BY CHAITANYA SINGH | FILED UNDER: C-PROGRAMMING

A pointer is a variable that stores the address of another variable. Unlike other variables that hold
values of a certain type, pointer holds the address of a variable. For example, an integer variable
holds (or you can say stores) an integer value, however an integer pointer holds the address of a
integer variable. In this guide, we will discuss pointers in C programming with the help of
examples.

Before we discuss about pointers in C, lets take a simple example to understand what do we
mean by the address of a variable.

A simple example to understand how to access the address of a variable without


pointers?
In this program, we have a variable num of int type. The value of num is 10 and this value must be
stored somewhere in the memory, right? A memory space is allocated for each variable that holds
the value of that variable, this memory space has an address. For example we live in a house and
our house has an address, which helps other people to find our house. The same way the value of
the variable is stored in a memory address, which helps the C program to find that value when it is
needed.

So let’s say the address assigned to variable num is 0x7fff5694dc58, which means whatever value we
would be assigning to num should be stored at the location: 0x7fff5694dc58. See the diagram below.

#include <stdio.h>
int main()
{
int num = 10;
printf("Value of variable num is: %d", num);
/* To print the address of a variable we use %p
* format specifier and ampersand (&) sign just
* before the variable name like &num.
*/
printf("\nAddress of variable num is: %p", &num);
return 0;
}
Output:

Value of variable num is: 10


Address of variable num is: 0x7fff5694dc58
A Simple Example of Pointers in C
This program shows how a pointer is declared and used. There are several other things that we
can do with pointers, we have discussed them later in this guide. For now, we just need to know
how to link a pointer to the address of a variable.

Important point to note is: The data type of pointer and the variable must match, an int pointer
can hold the address of int variable, similarly a pointer declared with float data type can hold the
address of a float variable. In the example below, the pointer and the variable both are of int type.

#include <stdio.h>
int main()
{
//Variable declaration
int num = 10;

//Pointer declaration
int *p;

//Assigning address of num to the pointer p


p = #

printf("Address of variable num is: %p", p);


return 0;
}
Output:

Address of variable num is: 0x7fff5694dc58

C Pointers – Operators that are used with Pointers


Lets discuss the operators & and * that are used with Pointers in C.

“Address of”(&) Operator


We have already seen in the first example that we can display the address of a variable using
ampersand sign. I have used &num to access the address of variable num. The & operator is also
known as “Address of” Operator.

printf("Address of var is: %p", &num);


Point to note: %p is a format specifier which is used for displaying the address in hex format.
Now that you know how to get the address of a variable but how to store that address in some
other variable? That’s where pointers comes into picture. As mentioned in the beginning of this
guide, pointers in C programming are used for holding the address of another variables.

Pointer is just like another variable, the main difference is that it stores address of another
variable rather than a value.

“Value at Address”(*) Operator


The * Operator is also known as Value at address operator.
How to declare a pointer?

int *p1 /*Pointer to an integer variable*/


double *p2 /*Pointer to a variable of data type double*/
char *p3 /*Pointer to a character variable*/
float *p4 /*pointer to a float variable*/
The above are the few examples of pointer declarations. If you need a pointer to store the
address of integer variable then the data type of the pointer should be int. Same case is with
the other data types.

By using * operator we can access the value of a variable through a pointer.


For example:

double a = 10;
double *p;
p = &a;
*p would give us the value of the variable a. The following statement would display 10 as output.

printf("%d", *p);
Similarly if we assign a value to *pointer like this:

*p = 200;
It would change the value of variable a. The statement above will change the value of a from 10 to
200.

Example of Pointer demonstrating the use of & and *


#include <stdio.h>
int main()
{
/* Pointer of integer type, this can hold the
* address of a integer type variable.
*/
int *p;

int var = 10;

/* Assigning the address of variable var to the pointer


* p. The p can hold the address of var because var is
* an integer type variable.
*/
p= &var;

printf("Value of variable var is: %d", var);


printf("\nValue of variable var is: %d", *p);
printf("\nAddress of variable var is: %p", &var);
printf("\nAddress of variable var is: %p", p);
printf("\nAddress of pointer p is: %p", &p);
return 0;
}
Output:

Value of variable var is: 10


Value of variable var is: 10
Address of variable var is: 0x7fff5ed98c4c
Address of variable var is: 0x7fff5ed98c4c
Address of pointer p is: 0x7fff5ed98c50

Lets take few more examples to understand it better –


Lets say we have a char variable ch and a pointer ptr that holds the address of ch.

char ch='a';
char *ptr;
Read the value of ch

printf("Value of ch: %c", ch);


or
printf("Value of ch: %c", *ptr);
Change the value of ch

ch = 'b';
or
*ptr = 'b';
The above code would replace the value ‘a’ with ‘b’.

Can you guess the output of following C program?

#include <stdio.h>
int main()
{
int var =10;
int *p;
p= &var;

printf ( "Address of var is: %p", &var);


printf ( "\nAddress of var is: %p", p);

printf ( "\nValue of var is: %d", var);


printf ( "\nValue of var is: %d", *p);
printf ( "\nValue of var is: %d", *( &var));

/* Note I have used %p for p's value as it represents an address*/


printf( "\nValue of pointer p is: %p", p);
printf ( "\nAddress of pointer p is: %p", &p);
return 0;
}
Output:

Address of var is: 0x7fff5d027c58


Address of var is: 0x7fff5d027c58
Value of var is: 10
Value of var is: 10
Value of var is: 10
Value of pointer p is: 0x7fff5d027c58
Address of pointer p is: 0x7fff5d027c50
More Topics on Pointers
1) Pointer to Pointer – A pointer can point to another pointer (which means it can store the
address of another pointer), such pointers are known as double pointer OR pointer to pointer.

2) Passing pointers to function – Pointers can also be passed as an argument to a function,


using this feature a function can be called by reference as well as an array can be passed to a
function while calling.

3) Function pointers – A function pointer is just like another pointer, it is used for storing the
address of a function. Function pointer can also be used for calling a function in C program.

Accessing array elements(Traversing array) by


incrementing a Pointer
Name of the array refers to the base address of the array.
Here we have a tutorial to understand How Pointer arithmetic works?
Below is a program to access elements of an array using pointer increment.
#include <stdio.h>

const int MAX = 3; // Global declaration


int main()
{
printf("\n\n\t\tStudytonight - Best place to learn\n\n\n");
int var[] = {100, 200, 300};
int i, *ptr;

/*
storing address of the first element
of the array in pointer variable
*/
ptr = var;

for(i = 0; i < MAX; i++)


{
printf("\n\n\nAddress of var[%d] = %x ", i, ptr);
printf("\nValue of var[%d] = %d ", i, *ptr);

// move to the next location


ptr++;
}
printf("\n\n\t\t\tCoding is Fun !\n\n\n");
return 0;
}

Output:

Traversing array elements by decrementing a


Pointer
Below is a program to access elements of an array using pointer decrement.
#include <stdio.h>

const int MAX = 3; // Global declaration


int main()
{
printf("\n\n\t\tStudytonight - Best place to learn\n\n\n");
int var[] = {100, 200, 300};
int i, *ptr;

/*
storing address of the last element
of the array in pointer variable
*/
ptr = &var[MAX-1];

for(i = MAX; i > 0; i--)


{
printf("\n\n\nAddress of var[%d] = %x ", i, ptr);
printf("\nValue of var[%d] = %d ", i, *ptr);

// move to the previous location


ptr--;
}
printf("\n\n\t\t\tCoding is Fun !\n\n\n");
return 0;
}

Output:
C - Pointers and Strings

In this tutorial we will learn to store strings using pointers in C programming


language.
We know that a string is a sequence of characters which we save in an array. And in
C programming language the \0 null character marks the end of a string.

Creating a string
In the following example we are creating a string str using char character array of
size 6.

char str[6] = "Hello";

The above string can be represented in memory as follows.

Each character in the string str takes 1 byte of memory space.

Creating a pointer for the string


The variable name of the string str holds the address of the first element of the array
i.e., it points at the starting memory address.
So, we can create a character pointer ptr and store the address of the
string str variable in it. This way, ptr will point at the string str.
In the following code we are assigning the address of the string str to the
pointer ptr.

char *ptr = str;

We can represent the character pointer variable ptr as follows.


The pointer variable ptr is allocated memory address 8000 and it holds the address
of the string variable str i.e., 1000.

Accessing string via pointer


To access and print the elements of the string we can use a loop and check for
the \0 null character.
In the following example we are using while loop to print the characters of the string
variable str.

#include <stdio.h>

int main(void) {

// string variable

char str[6] = "Hello";

// pointer variable

char *ptr = str;

// print the string

while(*ptr != '\0') {

printf("%c", *ptr);

// move the ptr pointer to the next memory location

ptr++;

return 0;
}

Using pointer to store string


We can achieve the same result by creating a character pointer that points at a string
value stored at some memory location.
In the following example we are using character pointer variable strPtr to store
string value.

#include <stdio.h>

int main(void) {

// pointer variable to store string

char *strPtr = "Hello";

// temporary pointer variable

char *t = strPtr;

// print the string

while(*t != '\0') {

printf("%c", *t);

// move the t pointer to the next memory location

t++;

return 0;

}
Note! In the above code we are using another character pointer t to print the
characters of the string as because we don't want to lose the starting address of the
string "Hello" which is saved in pointer variable strPtr.

In the above image the string "Hello" is saved in the memory location 5000 to 5005.
The pointer variable strPtr is at memory location 8000 and is pointing at the string
address 5000.
The temporary variable is also assigned the address of the string so, it too holds the
value 5000 and points at the starting memory location of the string "Hello".

Array of strings
We can create a two dimensional array and save multiple strings in it.
For example, in the given code we are storing 4 cities name in a string array city.

char city[4][12] = {

"Chennai",

"Kolkata",

"Mumbai",

"New Delhi"

};

We can represent the city array as follows.

The problem with this approach is that we are allocating 4x12 = 48 bytes memory to
the city array and we are only using 33 bytes.
We can save those unused memory spaces by using pointers as shown below.

char *cityPtr[4] = {

"Chennai",
"Kolkata",

"Mumbai",

"New Delhi"

};

In the above code we are creating an array of character pointer cityPtr of size 4 to
store the name of the four cities.
We can represent the array of pointers as follows.

The above array of pointers can be represented in memory as follows.

The cityPtr pointer variable is allocated the memory address 8000 to 8007.
Assuming integer address value takes 2 bytes space. So, each pointer gets 2 bytes.
Name of the cities are saved in locations 1000, 2000, 3000 and 4000.

Accessing values pointed by array of pointers


To access and print the values pointed by the array of pointers we take help of loop
as shown in the following example.

#include <stdio.h>

int main(void) {

// array of pointers

char *cityPtr[4] = {

"Chennai",

"Kolkata",
"Mumbai",

"New Delhi"

};

// temporary variable

int r, c;

// print cities

for (r = 0; r < 4; r++) {

c = 0;

while(*(cityPtr[r] + c) != '\0') {

printf("%c", *(cityPtr[r] + c));

c++;

printf("\n");

return 0;

Output:

Chennai

Kolkata

Mumbai

New Delhi

In the above code we are using the r variable to access each row of the pointer. And
we are using the c variable to access each character in a selected row.

You might also like