0% found this document useful (0 votes)
15 views90 pages

Pointers

Uploaded by

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

Pointers

Uploaded by

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

CSE101-PROBLEM SOLVING &

PROGRAMMING IN C
UNIT-4
POINTERS
Pointers and applications
• A pointer is a variable that represents the location of a data
item, such as a variable or an array element.
Applications:
• Pass information back and forth between an function and its
reference point
• Return multiple data items from a function, via function
arguments
• Reference to other functions through arguments
• Access individual array elements
Pointer fundamentals
• Data item occupies one or more contiguous memory cells.
• Example: pv = &v
• pv is the pointer variable stores address of another variable.
• Here, &-address operator
• pv- stores address of v, not a value
• v- stores value

Address of v Value of v

Pv = &v
u = *pv
Pointer example
#include<stdio.h>
main()
{
int u=3; →address identified automatically
int v;
int *pu, *pv; → pointer to u and pointer to v
pu=&u; → assign address of u to pu
v=*pu; → assign value of u to v
pv=&v; → assigns address of v to pv
printf(“u=%d &u=%x pu=%x *pu=%d”, u, &u, pu,*pu)
printf(“v=%d &v=%x pv=%x *pv=%d”, v, &v, pv,*pv)
}
Pointer fundamentals
• The precedence of & and * is same as unary operators,
associativity is from right to left.
• The address operator (&) act upon operands and are
associated with unique addresses.
• Not used for arithmetic expressions
• The indirection operator (*) can only act upon operands that
are pointers
Pointer example-2
#include<stdio.h>
main()
{
int u1, u2; Output:
int v=3; u1=16
int *pv; u2=16
u1=2*(v+5); → ordinary expression
pv=&v;
u2=2*(*pv+5); → equivalent expression (since v and *pv
represents same integer value)
printf(“u1=%d u2=%d”, u1, u2);
}
Pointer example-3
#include<stdio.h>
main()
{
Output:
int v=3;
*pv=3 v=3
int *pv;
*pv=0 v=0
pv=&v; Through *pv value of v
printf(“*pv=%d v=%d”, *pv, v); is changed to 0.
*pv=0;
printf(“*pv=%d v=%d”, *pv, v);
}
Pointer fundamentals

• Pointer variable point to →


numeric/char/arrays/functions/ other pointer
variable;
• The pointer variable can be assigned the address of
an ordinary variable or value of another pointer
variable
Pointer Declaration
• Pointer variable must be declared before they may be used.
• When a pointer variable is declared, the variable name must be preceded by
an (*)
• The data type that appears in the declaration refers the data item that is
stored in the address represented y the pointer rather than the pointer itself.
• Syntax
data_type *pvar
• pvar→ name of the pointer variable
• Example:
float u, v;
float *pv;
Pointer Declaration
• With a variable declaration, a pointer variable can be initialized by
assigning in the address of another variable
• Example:
float u, v;
float *pv=&v;
• Example:
#define NULL 0
float u, v;
float *pv = NULL;
Dereference a pointer
• Once we have a pointer that points to a specific memory location,
• we can access or modify the values stored at that location by
dereferencing the pointer.
• To dereference a pointer, we use asterisk (*) symbol again Infront of the
pointer variable.
• Example:
printf(“%d\n”, *pv);
Pointer to a pointer
• A pointer can also point to another pointer variable, which is known as a
pointer to a pointer variable.
• We declare this by using two asterisks **
• Example:
int x = 42;
int *p = &x;
int **q = &p;
• Here, q is a pointer to a pointer.
• It points to the address of the p variable,
• Which in turn points to the address of the x variable.
Passing pointers to a function
• We can pass pointers to functions as arguments,
• which allows the function to modify the value of the original
variable passed in.
• This is known as "passing by reference“ (passing arguments by
reference or by address or by location).
• Formal pointer arguments must be preceded by an *
• similarly in function prototype
• If function declaration does not include variable names, the data
type of each pointer argument must be followed by an *
Passing pointers to a function
• To pass a pointer to a function, we simply declare the function parameter as a pointer.
• For example:
void increment(int *p) • Here, the increment function takes a
{ pointer to an integer (int *p) and
(*p)++;
}
increments the value of the integer by
one ((*p)++).
int main() {
int x = 42; • In main(), we declare the integer x and
int *p = &x; a pointer p that points to x. We then
increment(p);
call the increment function, passing in
printf("%d\n", x); // prints 43
return 0;
the p pointer. After the function call, x
} has been incremented to 43.
Call by value
• In call by value method of parameter passing, the values of actual
parameters are copied to the function’s formal parameters.
• There are two copies of parameters stored in different memory
locations.
• One is the original copy and the other is the function copy.
• Any changes made inside functions are not reflected in the actual
parameters of the caller.
#include<stdio.h>
Call by value-Example
void change(int num) ;
Output:
int main() { Before function call x=100
int x=100; Before adding value inside function num=100
printf("Before function call x=%d \n", x); After adding value inside function num=200
change(x); //passing value in function After function call x=100
printf("After function call x=%d \n", x);
return 0;
}
void change(int num) {
printf("Before adding value inside function num=%d \n",num);
num=num+100;
printf("After adding value inside function num=%d \n", num);
}
Call by value-Example-swapping of two variables
#include <stdio.h>
void swap(int , int); //prototype of the function
int main()
{
int a = 10;
int b = 20;
printf("Before swapping the values in main a = %d, b = %d\n",a,b); // printing the val
ue of a and b in main
swap(a,b);
printf("After swapping values in main a = %d, b = %d\n",a,b); // The value of actual p
arameters do not change by changing the formal parameters in call by value, a = 10, b =
20
}
Call by value-Example-swapping of two variables
void swap (int a, int b)
{
int temp;
temp = a;
a=b;
b=temp;
printf("After swapping values in function a = %d, b = %d\n",a,b); // Formal parameter
s, a = 20, b = 10
}
Output:
Before swapping the values in main a = 10, b = 20
After swapping values in function a = 20, b = 10
After swapping values in main a = 10, b = 20
Call by reference
• In call by reference method of parameter passing, the
address of the actual parameters is passed to the function as
the formal parameters.
• Both the actual and formal parameters refer to the same
locations.
• Any changes made inside the function are actually reflected
in the actual parameters of the caller.
• Here the pointer is passed to a function
• Address is passed to a function
• The content of the address can be accessed freely either
within the function or calling function.
#include<stdio.h>
Call by reference-Example
void change(int *num) {
printf("Before adding value inside function num=%d \n",*num);
(*num) += 100;
printf("After adding value inside function num=%d \n", *num);
}
int main() {
Output:
int x=100; Before function call x=100
printf("Before function call x=%d \n", x); Before adding value inside function num=100
change(&x); //passing reference in function After adding value inside function num=200
After function call x=200
printf("After function call x=%d \n", x);
return 0;
}
Call by reference-Example-swapping of two variables
#include <stdio.h>
void swap(int *, int *); //prototype of the function
int main()
{
int a = 10;
int b = 20;
printf("Before swapping the values in main a = %d, b = %d\n",a,b); // printing the val
ue of a and b in main
swap(&a, &b);
printf("After swapping values in main a = %d, b = %d\n",a,b); // The values of actual p
arameters do change in call by reference, a = 10, b = 20
}
Call by reference-Example-swapping of two variables
void swap (int *a, int *b)
{
int temp;
temp = *a;
*a=*b;
*b=temp;
printf("After swapping values in function a = %d, b = %d\n",*a,*b); // Formal parameters,
a = 20, b = 10
}
Output:
Before swapping the values in main a = 10, b = 20
After swapping values in function a = 20, b = 10
After swapping values in main a = 20, b = 10
Array pointers
• Array name is actually a pointer to the array.
• The array name represents the address of the first element in
the array
• Array name is treated as pointers when it is passed to a
function
• It is not necessary to precede the array name with an ‘&’
within the function call
• An array name that appears as a formal argument within a
function definition can be declared either as a pointer or as
an array of unspecified size
Array of pointers
• In C, a pointer array is a homogeneous collection of indexed pointer
variables that are references to a memory location.
• It is generally used in C Programming when we want to point at multiple
memory locations of a similar data type in our C program.
• We can access the data by dereferencing the pointer pointing to it.
• Syntax:
pointer_type *array_name [array_size];
Count the number of vowels, consonants, digits, whitespace
characters and other characters in a line of text
#include<stdio.h>
#include<ctype.h>
void sline(char[], int*pv, int*pc, int*pd, int*pw, int*po);

main() {
char line[80];
int v=0; c=0; d=0; ws=0; ot=0;
printf("enter the line of text:");
scanf("%[\n]", line);
sline (line, &v, &c, &d, &ws, &ot);
printf("no of vowels:%d",v);
printf("no of consonants:%d",c);
printf("no of digits:%d",d);
printf("no of whitespaces:%d",ws);
printf("no of others:%d",ot);
}
Count the number of vowels, consonants, digits, whitespace
characters and other characters in a line of text
void sline(char[], int*pv, int*pc, int*pd, int*pw, int*po)
{
while((c=toupper(line[count]))!='\0')
{
if (c=='A'||c=='E'||c=='I'||c=='O'||c=='U')
*pv++;
elseif (c=='A'&&c=='z')
*pc++;
elseif (c=='0'&&c=='9')
*pd++;
elseif (c==' '|| c=='\t')
*pw++;
else
*po++;
count++;
} return; }
Array pointers-points to ponder
• In scanf() the array name not require ‘&’, because the array
names themselves represent addresses.
#include<stdio.h>
main()
{
char item[20];
int partno;
float cost;
scanf(“%s %d %f”, item, &partno, &cost);
}
Array pointers-points to ponder
• If the scanf() is used to enter a single array element rather
than an entire array, the name of the array element must be
preceded by an &.
• scanf(“%f”, &list[count]);
• It passes a portion of an array, rather than an entire array to a
function.
• The address of the first array element to be passed must be
specified as an argument.
• The reminder of the array, starting with the specified array
element, will then be passed to the function.
Array pointers-points to ponder
• For example,
#include<stdio.h>
void process(float z[]);
main()
{
float z[100];
:
process(&z[50]); \\ the address of z[50] is passed to the function process.
}
void process(float f[])
{
….
……..
return;
}
Array pointers-points to ponder
• The function can return a pointer to the calling portion of the
program.
• The function name must be precede with *, it must appear in
both the function definition and declaration.
#include<stdio.h>
double *scan(double f[]) \\ function
double *scan(double z[]); will return a pointer
main() {
{ double *pf;
double z[100]; pf = …..;
double *pz; return(pf);
pz = scan (z); }
}
Pointers and one-dimensional array
• Address of first array &x[0] or x
• Address of second array &x[1] or (x+1)
• Address of i-th array &x[i] or (x+i)
• These are the two different ways to write an address of an array
elements
• x[i] and *(x+i)→ represents the contents of that address
Pointers and one-dimensional array
#include<stdio.h>
main()
{
static int x[10]={10,11,12,13,14,15,16,17,18,19};
int i;
for(i=0;i<=9;i++)
{
printf(“i=%d x[i]=%d *(x+i)=%d”, i, x[i], *(x+i) );
printf(“&x[i]=%u x+i=%u”, &x[i], (x+i) );
}
}
Pointers and one-dimensional array-example
#include<stdio.h>
main()
{
int line[80];
int *pl;
…..
line[2]=line[1];
line[2]=*(line+1);
*(line+2)=line[1];
*(line+2)=*(line+1);
pl=&line[1];
pl=line+1;
}
Pointers and one-dimensional array
&line[2] = &line[1];
• This is impossible, because the address of one array element cannot
be assigned to some other array element address directly.
• Instead of that below method is used,
pl=&line[1];
line[2]=*pl;
or
pl=line+1;
*(line+2)=*pl;
Pointers and one-dimensional array
• If a numerical array is defined as a pointer variable, the array
elements cannot be assigned initial values.
• Therefore, a conventional array definition is requires if initial values
will be assigned to the elements of a numerical array
• A char-type pointer variable can be assigned an entire string as a part
of the variable declaration
• String can be represented either a one-dimensional character array or
a character pointer.
Structures and pointers
• The way we can have a pointer pointing to an int, or a pointer pointing to a char, similarly
we can have a pointer pointing to a struct. Such pointers are known as ‘structure pointers’.
• By using ‘&’ to access the beginning address of structure
• Syntax:
type *ptvar;
• Then assign the address of structure variable to pointer by,
ptvar = &variable;
• The variable and pointer declaration can be combined by,
struct { Example:
member 1; struct {
member 2;
int acct_no;
……..
char name[10];
member m;
} variable, *ptvar; } customer, *pc;
pc = &customer;
Structures and pointers
• To access the individual structure member by using pointer is
ptvar→member
• equal to variable.member
• ‘→’ operator is a highest precedence operator and associativity is from left to
right
• ‘→’ and (.) operator are combined to access submember
ptvar→ member.submember
• ‘→’ used for accessing array element
ptvar→member[exp]
Structures and pointers
struct {
typedef struct { int acct_no;
int month; char acct_type;
int day; char name[80];
int year; float balance;
date lastpayment;
} date;
} customer, *pc = &customer;
record customer[100];
• To access a member in different ways,
• customer.name
• pc→name
• (*pc).name → use parenthesis because (.) has highest precedence than *
Structures and pointers
• to access specific element in an array
customer.name[2] pc→name[2] (*pc).name[2]
or
*(customer.name+2) pc→(name+2) *((*pc).name+2)
• To access nested structures
customer.lastpayment.month
or
pc→lastpayment.month
or
(*pc).lastpayment.month
#include<stdio.h>
Structures and pointers-example
strcut employee{
char name[30]; printf(“name:%s”, ptr→name);
printf(“id:%d”, ptr→id);
int id; printf(“age:%d”, ptr→age);
int age; return 0;
} emp1, *ptr1;
}
int main()
{
ptr = &emp1;
printf(“enter name:”);
scanf(“%s”, &ptr→ name);
printf(“enter id:”);
scanf(“%d”, &ptr→ id);
printf(“enter age:”);
scanf(“%d”, &ptr→ age);
#include<stdio.h> Structures and pointers-example
main()
customer.acct_no = &n;
{
customer.acct_type=&t;
int n=3333; customer.name=“Renu”
char t=‘C’; customer.balance=&b;
printf(“%d %c %s %.2f\n” customer. *acct_no,
float b=99.99;
customer. *acct_type,
typedef strcut{ customer.name,
int month; *customer.balance);
printf(“%d %c %s %.2f\n” *pc→acct_no,
int day;
*pc →acct_type,
int year; pc→name,
} date; *pc→balance);
struct {
}
int *acct_no;
char *acct_type;
char *name;
float *balance;
date lastpayment; } customer, *pc=&customer;
Structures and pointers
• Structure can include one or more pointers as members
• ptmember→ both a pointer and member of variable
• *variable.ptmember → it will access the value to which ptmember points
• ptvar→ pointer variable→ it points to the structure
• &ptmember→ it is a member of that structure
• then, *ptvar→ptmember will access the value to which ptmember points
• ++ptvar→member – will increase number of bytes
• ++(ptvar→member)
• ++ptvar→member.submember
• ++(ptvar→member.submember)
#include<stdio.h>
Structures and pointers-example
#include<stdlib.h>
struct emp{ {
printf(“enter name:”);
char name[30]; scanf(“%s”, (ptr+i)→ name);
int id; printf(“enter id:”);
int age; scanf(“%d”, &(ptr+i)→ id);
printf(“enter age:”);
} *ptr1; scanf(“%d”, &(ptr+i)→ age);
int main() }
{ for(i=o, i<n; i++)
{
int i,n; printf(“name:%s”, (ptr+i)→name);
printf(“enter num of employee:”); printf(“id:%d”, (ptr+i)→id);
scanf(“%d”, &n); printf(“age:%d”, (ptr+i)→age);
return 0;
ptr1 = (struct emp *) malloc(sizeof(struct emp));
}
for(i=o, i<n; i++)
Self-Referential Structures
• Self-Referential structures are those structures that have one or more
pointers which point to the same type of structure, as their member.
• To include within a structure one member that is a pointer to the parent
structure type.
• Syntax:
struct tag{
member1;
member2;
…..
struct tag *name
};
• here tag denotes point to another structure of type tag
Self-Referential Structures
Example:
struct list_element {
char item[40];
struct list_element *next; \\ pointer structure of the same type \\
self-referential structure
};
• struct list_element *next; denotes pointer structure of the same type which
is a self-referential structure.
• Self-referential structure is useful in linked data structures like trees and lists.
Self-Referential Structures
• Linked data structures→ each component within the structure includes a
special points
• Points to the next component can be found
• The relative order can be easily changed by altering the pointers
• Individual components can easily be added or deleted by altering the pointers
• Data structures can be expand or contract in size as required
Types of linked list:
• Linear linked list→ components linked in sequential order
• Doubly/multiple pointer linked list→ forward & backward
• Circular linked list→ no beginning & no ending
• Trees→ components are arranged in hierarchical order
Dynamic Memory Allocation
• Conventional array name→ pointer to the first element within the array
• Able to declare with pointer variable
• Conventional and pointer variable declarations are syntactically correct but
the memory allocation procedure may differ.
• In conventional array definition, fixed block of memory being reserved at
the beginning of the program execution
• The use of pointer variable to represent an array requires some type of
initial memory assignment before the array elements are processed
• which is known as dynamic memory allocation
• Done by malloc()
Dynamic Memory Allocation
• Example: int *x; which is same as int x[10];
• int*x; → memory space not automatically assigned; to assign 10
memory space in advance, x is defined as an array.
• int x[10]; → 10 memory space is allocated for storage
• To assign sufficient memory for x, use the library function malloc()
x=(int *)malloc(10*sizeof(int));
• int * is datatype of pointer variable
• Allocate 10 memory space and return pointer (indicate the beginning
of the memory block) to an integer
x=(double *)malloc(10*sizeof(double));
Dynamic Memory Allocation
• If the declaration includes the assignment of initial values, x must
include/define as an array rather than a pointer variable
int x[10] = {1,2,3,4,5,6,7,8,9,10};
or
int x[ ] = {1,2,3,4,5,6,7,8,9,10};
Dynamic Memory Allocation-Example
#include <stdio.h>
#include <stdlib.h>
int main()
{
// This pointer will hold the base address of the block created
int* ptr;
int n, i;
// Get the number of elements for the array
printf("Enter number of elements:");
scanf("%d",&n);
printf("Entered number of elements: %d\n", n);
// Dynamically allocate memory using malloc()
ptr = (int*)malloc(n * sizeof(int));
Dynamic Memory Allocation-Example
// Check if the memory has been successfully allocated by malloc or not
if (ptr == NULL) {
printf("Memory not allocated.\n");
exit(0);
}
else {

// Memory has been successfully allocated


printf("Memory successfully allocated using malloc.\n");
Dynamic Memory Allocation-Example
// Get the elements of the array
for (i = 0; i < n; ++i) {
ptr[i] = i + 1;
}
// Print the elements of the array
printf("The elements of the array are: ");
for (i = 0; i < n; ++i) {
printf("%d, ", ptr[i]);
}
}

return 0;
}
Advantages of Dynamic Memory Allocation
• The ability to reserve as much as memory as may be required during
the execution of the program
• and then release this memory when it is no longer needed
Memory allocation→ malloc()
Release or deallocation → free()
• These functions can be repeated many number of times during the
program execution
Operations on pointers (Pointer Arithmetic)
• Pointer Arithmetic is the set of valid arithmetic operations that can be
performed on pointers.
• The pointer variables store the memory address of another variable.
• It doesn’t store any value.
• Hence, there are only a few operations that are allowed to perform
on Pointers in C language.
Operations on pointers (Pointer Arithmetic)
• The C pointer arithmetic operations are slightly different from the
ones that we generally use for mathematical calculations.
• These operations are:
1.Increment/Decrement of a Pointer
2.Addition of integer to a pointer
3.Subtraction of integer to a pointer
4.Subtracting two pointers of the same type
5.Comparison of pointers
Increment/decrement of a pointers
• Increment :When a pointer is incremented, it actually increments by
the number equal to the size of the data type, for which it is a
pointer.
• For Example:
If an integer pointer that stores address 1000 is incremented, then it
will increment by 4(size of an int), and the new address will point
to 1004. While if a float type pointer is incremented then it will
increment by 4(size of a float) and the new address will be 1004.
Increment/decrement of a pointers
• Decrement: When a pointer is decremented, it actually decrements
by the number equal to the size of the data type for which it is a
pointer.
• For Example:
If an integer pointer that stores address 1000 is decremented, then it
will decrement by 4(size of an int), and the new address will point
to 996. While if a float type pointer is decremented then it will
decrement by 4(size of a float) and the new address will be 996.
Increment/decrement of a pointers
Increment/decrement of a pointers
#include <stdio.h>
int main()
{
int a = 22;
int *p = &a;
printf("p = %u\n", p); // p = 6422288
p++;
printf("p++ = %u\n", p); //p++ = 6422292 +4 // 4 bytes
p--;
printf("p-- = %u\n", p); //p-- = 6422288 -4 // restored to original value
Increment/decrement of a pointers
float b = 22.22;
float *q = &b;
printf("q = %u\n", q); //q = 6422284
q++;
printf("q++ = %u\n", q); //q++ = 6422288 +4 // 4 bytes
q--;
printf("q-- = %u\n", q); //q-- = 6422284 -4 // restored to original value
Increment/decrement of a pointers
char c = 'a';
char *r = &c;
printf("r = %u\n", r); //r = 6422283
r++;
printf("r++ = %u\n", r); //r++ = 6422284 +1 // 1 byte
r--;
printf("r-- = %u\n", r); //r-- = 6422283 -1 // restored to original value

return 0;
}
Addition of pointers
• When a pointer is added with an integer value, the value is first
multiplied by the size of the data type and then added to the pointer.
• For Example:
Consider the same example as above where the ptr is an integer
pointer that stores 1000 as an address. If we add integer 5 to it using the
expression, ptr = ptr + 5, then, the final address stored in the ptr will
be ptr = 1000 + sizeof(int) * 5 = 1020.
Addition of pointers-example
#include <stdio.h>
// Addition of 3 to ptr2
int main() ptr2 = ptr2 + 3;
{ printf("Pointer ptr2 after Addition: ");
int N = 4; printf("%p \n", ptr2);
int *ptr1, *ptr2;
return 0;
// Pointer stores the address of N }
ptr1 = &N;
ptr2 = &N;
printf("Pointer ptr2 before Addition: ");
printf("%p \n", ptr2);
Subtraction of pointers
• When a pointer is subtracted with an integer value, the value is first
multiplied by the size of the data type and then subtracted from the
pointer similar to addition.
• For Example:
Consider the same example as above where the ptr is an integer
pointer that stores 1000 as an address. If we subtract integer 5 from it
using the expression, ptr = ptr – 5, then, the final address stored in the
ptr will be ptr = 1000 – sizeof(int) * 5 = 980..
Subtraction of two pointers
• The subtraction of two pointers is possible only when they have the same
data type.
• The result is generated by calculating the difference between the
addresses of the two pointers and calculating how many bits of data it is
according to the pointer data type.
• The subtraction of two pointers gives the increments between the two
pointers.
• For Example:
Two integer pointers say ptr1(address:1000) and ptr2(address:1004) are
subtracted. The difference between addresses is 4 bytes. Since the size of
int is 4 bytes, therefore the increment between ptr1 and ptr2 is given
by (4/4) = 1.
Subtraction of two pointers-example
#include <stdio.h>
// Subtraction of ptr2 and ptr1
int main() x = ptr1 - ptr2;
{
int x = 6; // Print x to get the Increment
// between ptr1 and ptr2
int N = 4; printf("Subtraction of ptr1 "
// Pointer declaration "& ptr2 is %d\n",
int *ptr1, *ptr2; x);
ptr1 = &N; // stores address of N return 0;
ptr2 = &x; // stores address of x }
Output:
printf(" ptr1 = %u, ptr2 = %u\n", ptr1, ptr2);
ptr1 = 2715594428,
// %p gives an hexa-decimal value, ptr2 = 2715594424
// We convert it into an unsigned int value by using %u Subtraction of ptr1 & ptr2 is 1
Comparison of pointers
• We can compare the two pointers by using the comparison operators in
C.
• We can implement this by using all operators in C >, >=, <, <=, ==, !=.
• It returns true for the valid condition and returns false for the unsatisfied
condition.
1.Step 1: Initialize the integer values and point these integer values to the
pointer.
2.Step 2: Now, check the condition by using comparison or relational
operators on pointer variables.
3.Step 3: Display the output.
Comparison of pointers
#include <stdio.h>
int main()
{
// declaring array
int arr[5];

// declaring pointer to array name


int* ptr1 = &arr;
// declaring pointer to first element
int* ptr2 = &arr[0];

if (ptr1 == ptr2) {
printf("Pointer to Array Name and First Element "
"are Equal.");
}
Comparison of pointers
#include <stdio.h>
int main() if (ptr1 == ptr2) {
{ printf("Pointer to Array Name and First Element "
// declaring array "are Equal.");
}
int arr[5]; else {
printf("Pointer to Array Name and First Element "
// declaring pointer to array name "are not Equal.");
}
int* ptr1 = &arr;
// declaring pointer to first element return 0;
int* ptr2 = &arr[0]; }
Permissible operations
• A pointer variable can be assigned the address of an ordinary variable
(eg: pv=&v).
• A pointer variable can be assigned the value of another pointer variable
(pv=px), provided both pointers of same data type
• A pointer variable can be assigned a null value (pv=Null), Such pointers
are called NULL pointers and are used in various pointer-related error-
handling methods.
• An integer variable can be added to or subtracted from a pointer
variable(eg:pv+3)
• Other arithmetic operations are not allowed
• Pointer variables cannot be multiplied by constant, two pointer variables
cannot be added
Pointers and Multidimensional arrays
• Define a two-dimensional array as a pointer to a group of contiguous
one-dimensional arrays
• Syntax
data_type (*ptvar) [exp2]; → array name with pointer declaration
rather than
data_type array [exp 1] [exp2];
• The generalized representation is
data_type (*ptvar) [exp2] [exp3]…. [expn];
replaces,
data_type array [exp1] [exp2]…. [expn];
Pointers and Multidimensional arrays
• Let’s declare a 3x3 array
• int arr[3] [3];
• Lets assume the starting address of the above 2d array is 1000.
• Visual representation,
Pointers and Multidimensional arrays
• &arr is a whole 2D array pointer
• &arr is a pointer to the entire array 2d(3x3).
• i.e. (int*)[3][3];
• If we move &arr by 1 position (&arr+1), it will point to the next 2d block
(3x3)
• In our case, the base address of the 2d array is 1000.
• So, &arr value will be 1000.
• What will be the value of &arr+1?
• In general, for Row x Col array, the formula will be
base address + (Row * Col) * sizeof(array datatype)
• In our case, Row = 3, Col = 3, sizeof(int) = 4.
• It is base address + (3 * 3)* 4 => 1000 + 36 => 1036
Pointers and Multidimensional arrays
Pointers and Multidimensional arrays
• *arr is a pointer to the first element of the 2D array. i.e. (int*)
• If we move *arr by 1 position(*arr+1), it will point to the next element.
• The base address of the first element also 1000.
• So, *arr value will be 1000.
• What will be the value of *arr+1?
• It will be base address + sizeof(datatype).
• 1000 + 4
• 1004
Pointers and Multidimensional arrays
Pointers and Multidimensional arrays
• **arr will be the value of the first element.
• Since *arr holds the address of the first element, **arr will give the value
stored in the first element.
• If we move **arr by 1 position(**arr+1), the value will be incremented by
1.
• If the array first element is 10, **arr+1 will be 11.
Pointers and Multidimensional arrays-summary
• &arr is a 2D array pointer (int*)[row][col]. So, &arr+1 will point the next
2D block.
• arr is a 1D array pointer (int*)[row]. So, arr+1 will point the next 1D array
in the 2D array.
• *arr is a single element pointer (int*). So, *arr+1 will point the next
element in the array.
• **arr is the value of the first element. **arr+1 will increment the
element value by 1.
Pointers and Multidimensional arrays-example
#include <stdio.h>
Adding two tables of numbers
#include<stdlib.h>
#define MAXROWS 20
void readinput(int *a[MAXROWS], int nrows, int ncols);
void computesums(int *a[MAXROWS], int *b[MAXROWS], int *c[MAXROWS], int nrows, int ncols);
void writeoutput(int *c[MAXROWS], int nrows, intncols);
main()
{
int row, nrows, ncols;
int *a[MAXROWS], int *b[MAXROWS], int *c[MAXROWS];
printf("how many rows?");
scanf("%d",&nrows);
printf("how many columns?");
scanf("%d",&ncols);
Pointers and Multidimensional arrays-example
Adding two tables of numbers
for(row=0;row<nrows;row++)
{
a[row]=(int *) malloc(ncols*sizeof(int));
b[row]=(int *) malloc(ncols*sizeof(int));
c[row]=(int *) malloc(ncols*sizeof(int));
}
printf("first table");
readinput(a, nrows, ncols);
printf("second table");
readinput(b, nrows, ncols);
computesum(a,b,c,nrows,ncols);
printf("the sum of the elements");
readinput(c, nrows, ncols);
}
Pointers and Multidimensional arrays-example
Adding two tables of numbers
void readinput(int *a[MAXROWS], int m, int n);
{
int row,col;
for(row=0;row<m;row++)
{
printf("enter data for row");
for(col=0;col<n;col++)
scanf("%d", (*(a+row)+col));
}
return;
}
Pointers and Multidimensional arrays-example
Adding two tables of numbers
void computesums(int *a[MAXROWS], int *b[MAXROWS], int *c[MAXROWS] int m, int n);
{
int row,col;
for(row=0;row<m;row++)
for(col=0;col<n;col++)
*(*(c+row)+col)=*(*(a+row)+col) + *(*(b+row)+col);
return;
}
Pointers and Multidimensional arrays-example
Adding two tables of numbers
void writeoutput(int *c[MAXROWS], int m, int n);
{
int row, col;
for(row=0;row<m;row++)
{
for(col=0;col<n;col++)
printf("%d", *(*(c+row)+col));
}
return;
}
Array of pointers
• A 2d array can be defined as a 1d array of pointers by writing
datatype *array[exp1];
• N-dimensional array of pointers→ datatype *array[exp1];
• Pointer to group of array→ datatype *(array)[exp2];
• When an n-dimensional array id expressed in array of pointers, an
individual array element within the n-dimensional array can be accessed
by a single use of the indirection operator.
• Example: int *x[10]; → number of rows and number of column
declaration not required here. It is calculated using malloc()
• x[i]=(int *) malloc(number_of_columns*sizeof(int));
Array of pointers-example
#include<stdio.h> Reordering a list of strings
#include<stdlib.h>
#include<string.h>
void reorder(int n, char *x[]);
main()
{
int i, n=0;
char *x[10];
do{
x[n]=(char *)malloc(12*sizeof(char));
printf("string %d, n+1");
scanf("%s", x[n]);
}
Array of pointers-example
Reordering a list of strings
while(strcmp(x[n+1], "END"));
reorder(--n, x);
printf("reordered list of strings/n");
for(i=0;i<n;i++)
printf("%s", x[i]);
}
Array of pointers-example
Reordering a list of strings
void reorder(int n, char *x[]);
{
char *temp;
int i, item;
for(item=0;item<n-1;item++)
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; }
More about pointer declaration
• Nesting function→ indicates a function that accepts an integer argument,
and returns a pointer to an integer
• int *p(int a);
• int (*p)(int a); → pointer to a function that accepts an integer argument
and returns an integer
• int *(*p) (int(*a)[ ]); → pointer to a function
• int *(*p) ( ) → pointer to a function that returns a pointer to an integer
• (*a) [ ]→ pointer to an array
More pointer declaration
• int(*a) [ ]→ pointer to an array of integer
• (*p)(int(*a) [ ])→ pointer to a function whose argument is a pointer to
an array of integers
• int *(*p) (int(*a) []); →pointer to a function that accepts a pointer to an
array of integers, and returns a pointer to an integer
• int*p; →pointer to an integer
• int*p [10]; → 10 element array of pointers to an integer
• int (*p) [10]; → pointer to an 10-element integer array
• int *p(void); → p is a function returns a pointer to an integer
• int p(char *a); → returns integer
• int *p(char a*);→ returns pointer to integer
• int (*p) (char *a);→ pointer to a function
More pointer declaration
• int (*p (char *a)) [10]; → returns pointer to a 10-element integer
• int p(char *a[]);
• int *p (char a[]);
• int *p (char (*a) []);
• int *p (char *a[]);
• int (*p) (char (*a) []);
• int *(*p) (char (*a) []);
• int *(*p) (char *a []);
• int (*p [10]) (void);
• int (*p [10]) (char a);
• int *(*p [10]) (char a);
• int *(*p [10]) (char *a);

You might also like