0% found this document useful (0 votes)
114 views

C Programming Topic: Pointers Module 1: Pointer Basics

This document provides an overview of pointers in C programming. It discusses pointer basics like indirection, declaring and initializing pointers, accessing variables through pointers, common pointer errors. It also covers pointer operations like expressions, arithmetic, arrays of pointers. The key topics are: 1) Pointers store the address of a variable. They are declared with a data type followed by an asterisk. 2) Pointers must be initialized with the address of a variable before being used. The address operator '&' returns the address of a variable. 3) The dereference operator '*' accesses the value at the address stored in the pointer. 4) Pointers allow passing arrays and structures to functions and dynamic memory allocation.

Uploaded by

seravanakumar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
114 views

C Programming Topic: Pointers Module 1: Pointer Basics

This document provides an overview of pointers in C programming. It discusses pointer basics like indirection, declaring and initializing pointers, accessing variables through pointers, common pointer errors. It also covers pointer operations like expressions, arithmetic, arrays of pointers. The key topics are: 1) Pointers store the address of a variable. They are declared with a data type followed by an asterisk. 2) Pointers must be initialized with the address of a variable before being used. The address operator '&' returns the address of a variable. 3) The dereference operator '*' accesses the value at the address stored in the pointer. 4) Pointers allow passing arrays and structures to functions and dynamic memory allocation.

Uploaded by

seravanakumar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 22

C Programming

Topic: Pointers
Module 1: Pointer Basics
Table of Content:
S. No Concept/Title
1 Concept of Pointer
1.1 Concept of Indirection
1.2 What is a Pointer?
1.3 Why Pointers?
1.4 The & and * Operators
2 Using Pointers
2.1 Declaring Pointers
2.2 Initializing Pointers
2.3 Accessing variables through Pointers
2.4 Common Errors While Using Pointers
2.5 Pointer to Pointer
3 Pointer Operations
3.1 Pointer Expressions
3.2 Pointer Arithmetic
3.3 Pointer & Arrays
3.4 Array of Pointers
3.5 Segmentation Fault
1. Concept of Pointer
1.1 Concept of Indirection

 To understand pointer, first we need to understand the concept of


Indirection
o Imagine in your office, you need a scanner
o You will place a request to the purchase department
o Purchase department will place an order to the local supplier and
gets the scanner for you
o That means, instead of yourself directly contacting the supplier and
getting it, you are getting the scanner indirectly through your
purchase department
o The same concept is used in pointers, where the values are
accessed indirectly

 What is the advantage?


o You have a single contact point for all your purchase needs
o Purchase department will have information of all suppliers
o They have well defined procedure to get the required item and the
process is reliable and efficient

1.2 What is a Pointer?

 A pointer is a variable that can hold address of another variable


 Let us see what exactly it means:
o We know that computer memory is collection of sequential storage
locations
o This storage location is called byte
o Each location will have an address
o A typical 32K memory consists of 32768 bytes
 First address is 0
 Last address is 32767
o A pointer is the variable that holds one of these addresses
 Let us consider the following statements:
o int x=10; /* Declaring & initializing integer variable */

It tells the compiler that


a) Reserve the space in memory to hold the integer value
b) Associate the name x with this memory location
c) Store the value 10 in this location

o int *ptr=&x; /* Declaring & initializing integer pointer */


It tells the compiler that
a) Reserve the space in memory to hold the address of a integer
variable
b) Associate the name ptr with this memory location
c) Store the address of x in this location

1.3 Why Pointers?

 Pointers are one of the most important and useful features of C


 Advantages of using pointers:
o Multiple values can be returned from a function
o Derived data types like arrays, structures, etc can be passed to
functions through pointers
o Multi - dimensional arrays can be easily represented in lower
dimensions
o Reduces the length and complexity of programs
o Increases the speed of execution
o Dynamic memory management
o Efficient handling of arrays and other data structures

1.4 The & and * Operators

 In the pointer programming, two operators are regularly used


o Address Operator (&): It is used to access address of any variable
o Dereferencing Operator (*): It is used to access the value stored in
a variable through its pointer
 Consider the same statement of previous section
int *ptr = &x;
In this declaration
o ‘*’ tells that ptr is a pointer to an integer variable ‘x’
o ‘&’ tells, store the address of x in this pointer variable

 Let us study the following program and its output


#include<stdio.h>
int main()
{
int x = 10;
int *iptr = &x;
printf("Address of x: %u\n", &x);
printf("Value in this address: %d\n", *iptr);
return 0;
}
/*Output:
Address of x: 37814108
Value in this address: 10
*/

 The first printf statement prints the address of the variable x


 The second printf statement prints the value stored in that address
2. Using Pointers

2.1 Declaring Pointers

 In the previous sections we have seen the usage of & and *


operators
 The ‘*’ operator has basically two roles
o As an indicator for a pointer variable
o Dereferencing ( obtaining the value ) a pointer variable for
its value
 A typical declaration statement will be in the form
data_type *v1, *v2, *v3;

Examples: int *x;


float *f;
 There are different styles of declaring pointers:
o int *p;
o int-* p;
o int* p;
Tip: All the three types are valid, but first style is preferred over
the other two because of readability and to avoid any
unexpected errors

2.2 Initializing Pointers


 The process of assigning an address to the pointer in the
declaration is called initialization
 Pointer variables are assigned using ‘&’ operator
Normal Method of Declaring Equivalent Initialization
and Assigning Values to a Statement
Pointer
int *p,x; int x, *p = &x;
p=&x;
float *fp, y; float y, *fp= &y;
fp=&y;
 It is necessary to assign an address to every pointer declared
before they are used

Q) Find the error if any in the following program


#include<stdio.h>
int main()
{
int *p;
*p = 10;
printf("The value of *p is %d:", *p);
}

ANS: This may lead to serious run time error. p is a pointer variable but it is not
referring (pointing) to any other variable. If a value is assigned directly, it may
use any unauthorized area in the memory which may lead to error or system
crash.

2.3 Accessing Variables through Pointers

 In the previous sections, we have seen the dereferencing


operator(*)
 This is also called indirection operator
 Values stored in a variable can be accessed using this operator
 Consider the following example:

#include<stdio.h>
int main()
{
int *p, x, num; // Two normal variables and one pointer
to integer variable are declared
p = &x; // Pointer variable is assigned the
address of
x = 100; // A value 100 is assigned to x
num = *p + 100; /* 100 is added to value of variable
referenced by p(100),
and the result (200) is assigned to num
*/
p= &num;
printf("%d", *p);
return 0;
}
Q) Can multiple pointers point to same variable?
Yes, any number of pointers can point to same variable

2.4 Common Errors While Using Pointers


1) Not initializing a pointer: A pointer which do not refer to any
variable is called Dangling pointer

int main()
{
int *p; /* p is not referring to any variable */
p=0; /* p is not a dangling pointer now */
}
 It is dangerous to leave a pointer without initialization
 It is always necessary to initialize pointers immediately after
declaration
 If there is no value to assign immediately, a pointer may be
initialized with NULL(0)

2) Assigning a value through dangling pointers:


int main()
{
int *p; /*p is a dangling pointer */
*p =10; /* cannot assign value through dangling
pointer */
}
3) Not clearing the memory after finishing the task:
 When the memory is allocated dynamically, a pointer is returned
for the allocated block
 It is necessary to clear it after our work is finished
 Otherwise, the memory block cannot be used and also may lead
to errors

int main()
{
char *st= malloc(20); /* st points to allocated array */
free(st); /* don’t forget to deallocate when finished */
}
2.5 Pointer to Pointer
 A pointer can store address of another pointer
 That means, one pointer can point to another pointer, which in
turn points to another pointer
 Declaring a pointer to pointer

int x=10, *p, **pp;


p=&x;
pp=&p;
#include<stdio.h>
int main()
{

int x, *p, **pp;


x = 10;
p = &x;
pp = &p;
printf("Address of x: %u\n", p);
printf("Value of x: %d\n", *p);
printf("Address of p: %u\n", pp);
printf("Value of p: %u\n", *pp);
printf("Address of pp: %u\n", &pp);
}
3. Pointer Operations
3.1 Pointer Expressions
 Pointers can be used as any other variables within expressions
 Expressions containing pointers are normally referred as pointer
expressions
 Examples:

Expression Meaning
x = *p1 + *p2; x is sum of values stored in variables pointed by p1
and p2
y = 2 * *p; y is product of 2 and value stored in variable pointed
by p
*p++; Value stored in variable pointed by p is incremented

 Caution: Use the pointers carefully within expressions. Leave a


blank space between dereferencing operator ‘*’ and other operators
of the expression.

a = 5 + *p1/*p2;
In this expression, the compiler treats ‘/*’ symbols as beginning of
the comment. This may lead to syntactical errors in the program.
The safe way of writing above expression is:

a = 5 + *p1/*p2;

Brackets may be used to avoid errors and better readability.

a= 5 + (*p1)/(*p2);

Tip: It is always safer to use brackets in pointer expressions.

Questions:
Identify errors if any in the following expressions. Rewrite the
expressions with and without using brackets.

1) sum = sum +*p;


Ans: No error. But, alternatively we can write as:
sum = sum + *p;
or
sum = sum + (*p);

2) total = total/*p1**p2;
Ans: Error. All characters after /* are treated as comments.

Correct method is:


total = total /*p1**p2;
or
total = total/(*p1)*(*p2);

3) *p2 = *p1 + 100;


Ans: No error. But, alternatively we can write as:
*p2 = *p1 + 100;
or
*p2 = (*p1) + 100;

4) Count + = *p;
Ans: No error. But, alternatively we can write as:
count + = *p;
or
count + = (*p);

3.2 Pointer ArithmeticIdentify errors if any in the following


expressions. Rewrite the expressions with and without using brackets.

 Arithmetic operations can be performed on pointers.


 Example:
p1 = p2 + 2;
p++;
n = p1 - p2;
Where p, p1, p2 are pointer variables to an array
Note: Pointers p1, p2 must refer to same array
 But some operations like multiplication, division, subtraction of
pointers are not possible.
The following are illegal statements:
p1 = p2 + p3;
p = p1 * p2;
p1 = p2/3;

Scale Factor:

 Whenever a pointer is incremented, that pointer will move its


reference to next value of that type.
 The length that is incremented by size of the data type of the
pointer.
 This length is called scale factor.

 For example, within an array:


o if pointer ptr is currently referring to 3rd element of the array
o then ptr++ causes ptr to change its position to 4th element of
the same array

 If ptr is a pointer to integer and current address is 150, ptr++ will


make ptr to move to address 152, because size of integer is 2 bytes.

Question:

If cptr is pointer to a string (character array), what is expression to


move to the 4th character of the string.
Ans: 4th character means, element with index 3. Scale factor for
character type is 1 byte. Therefore, cptr+ = 3; will move to the 4th
character of the string.

3.3 Pointers & Arrayssum = sum + *p;

 Consider the statements


int x[5] = {10,20,30,40,50};
int *p;
p = &x[0];

 The memory representation is as shown below:


x
x[0] x[1] x[2] x[3] x[4]
100
10 20 30 40 50

p 100 102 104 106 108

100
Base Address

 We know that:
o Array name is a pointer which contains the address of first
element of the array
o Elements of an array are stored in adjacent memory locations

Address of first element x[0] = 100


Address of second element x[1] = 102
Address of third element x[2] = 104

Element Address Value Accessing Accessing


Address Value
x[0] 100 10 p *p
x[1] 102 20 p+1 *(p + 1)
x[2] 104 30 p+2 *(p + 2)
x[3] 106 40 p+3 *(p + 3)
x[4] 108 50 p+4 *(p + 4)
Address of fourth element x[3] = 106
Address of fifth element x[4] = 108

The elements of the array can be accessed using pointer p


 From the above illustration, we can observe that:
o for each increment of pointer p, address is incremented by 2

 Reason:
o x is an integer array.
o Size of integer is 2 bytes.
o First element occupies memory locations 100 and 101.
o Next element occupies memory locations 102 and 103, so
on...

Question:

How can we get address of any particular element of the array?


Ans: Address of element with index n = base address + n x scale
factor
In the above illustration:
address of x[2] = 100 + 2 x 2 = 104

3.4 Array of Pointers

 Consider a situation, where we need to store a set of strings.


 Each string is character array.
 We may use array of pointers for this purpose.
Example:
 Let us say, we want store 4 metro cities, “NEWDELHI”,
“MUMBAI”, “CHENNAI”, “KOLKATA”.
 We may do this, using a 2 dimensional character array as shown
below:

char metros [4][10] = { “NEW DELHI”, “MUMBAI”,


“CHENNAI”, “KOLKATA”};
mptr

1000 N E W D E L H I \0
1010 M U M B A I \0
1020 C H E N N A I \0
1030 K O L K A T A \0
 Alternatively, we can use array of pointers as shown below
char *mptr[4]= { “NEW DELHI”, “MUMBAI”, “CHENNAI”,
“KOLKATA”};

mptr[0] refers to “NEW DELHI”


mptr[1] refers to “MUMBAI”
mptr[2] refers to “CHENNAI”
mptr[3] refers to “KOLKATA”

Solved Problem:
Write a program to sort the set of strings in alphabetical order using
array of pointers

#include<stdio.h>
#include<string.h>
#include<stdlib.h>
void sort(int n, char *x[]);
main()
{
int i, n = 0;
char *x[10];
printf("Enter each string on a separate line\n\n");
printf("Type \'end\' when finished\n\n");
/* read the list of strings */
do {
/* allocate memory */
x[n] = (char *) malloc(12 * sizeof(char));
printf("string %d:", n + 1);
scanf("%s", x[n]);
}while(strcmp(x[n++], "end"));
sort(n - 1, x);
for(i = 0; i < n; ++i)
printf("\nString %d %s", i + 1, x[i]);
}
void sort(int n, char *x[])
{

char *temp;
int i, item;
for (item = 0; item < n - 1; ++item)
/* Get lowest of all strings */
for (i = item + 1; i < n; ++i)
if (strcmp(x[item], x[i]) > 0){

temp = x[item];
x[item] = x[i];
x[i] = temp;
}
return;
}
3.5 Segmentation Fault
What is a segmentation fault?
 When your program runs, it has access to certain portions of
memory.
 Your program is only allowed to touch memory that belongs to
it.
 Any access outside that area will cause a segmentation fault.
 Segmentation faults are commonly referred to as segfaults.
 There are four common mistakes that lead to segmentation
faults:
o dereferencing a NULL or uninitialized pointer
o dereferencing a pointer that has been freed
o dereferencing a pointer that has gone out of scope of an
array
o a recursive function that uses all of the stack space

Summary:

 Address operator (&) is used to access address of variables.


 Dereferencing operator (*) is used to access value stored in a
variable through its pointer.
 A pointer variable can be assigned the address of another
variable.
 A pointer variable can be assigned the values of another pointer
variable.
 Pointers cannot be assigned a value directly. It must be assigned
using address operator.
 The only value that can be assigned to a pointer directly is
NULL (0).
 An integer may be added or subtracted from a pointer variable,
provided that pointer refers to an array.
 Array variable is a constant pointer. It cannot be incremented or
decremented.
 We can compare two pointers if both pointers are of same type.
 Similarly we can assign one pointer to another if both are of
same type.
 A pointer variable cannot be multiplied or divided.
 Two pointers cannot be added.
 It is dangerous to leave a pointer uninitialized.

Ans: No error. But, alternatively we can write as :


sum = sum + *p;
or
sum = sum + (*p);

5) total = total /*p1**p2;


Ans: Error. All characters after /* are treated as comments.

Correct method is:


total = total / *p1**p2;
or
total = total /(*p1)*(*p2);
6) *p2 = *p1 + 100;
Ans: No error. But, alternatively we can write as:
*p2 = *p1 + 100;
or
*p2 = (*p1) + 100;

7) Count + = *p;
Ans: No error. But, alternatively we can write as:
count + = *p;
or
count + = (*p);

You might also like