Unit 3
Unit 3
Arrays are used to store multiple values in a single variable, instead of declaring separate variables for
each value.
To create an array, define the data type (like int) and specify the name of the array followed by square
brackets [].
To insert values to it, use a comma-separated list, inside curly braces:
int myNumbers[] = {25, 50, 75, 100};
// Outputs 25
Example
int myNumbers[] = {25, 50, 75, 100};
myNumbers[0] = 33;
printf("%d", myNumbers[0]);
// Add elements
myNumbers[0] = 25;
myNumbers[1] = 50;
myNumbers[2] = 75;
myNumbers[3] = 100;
Using this method, you should know the size of the array, in order for the program to store enough
memory.
You are not able to change the size of the array after creation.
C Multidimensional Arrays
Multidimensional Arrays
In the previous chapter, you learned about arrays, which is also known as single dimension arrays. These
are great, and something you will use a lot while programming in C. However, if you want to store data as
a tabular form, like a table with rows and columns, you need to get familiar with multidimensional
arrays.
A multidimensional array is basically an array of arrays.
Arrays can have any number of dimensions. In this chapter, we will introduce the most common; two-
dimensional arrays (2D).
Two-Dimensional Arrays
A 2D array is also known as a matrix (a table of rows and columns).
To create a 2D array of integers, take a look at the following example:
int matrix[2][3] = { {1, 4, 2}, {3, 6, 8} };
The first dimension represents the number of rows [2], while the second dimension represents the number
of columns [3]. The values are placed in row-order, and can be visualized like this:
int i, j;
for (i = 0; i < 2; i++)
{
for (j = 0; j < 3; j++)
{
printf("%d", matrix[i][j]);
}
printf(“\n”);
}
o/p :
142
368
Example 2:
int matrix[2][3] = { {1, 4, 2}, {3, 6, 8} };
int i, j;
for (i = 0; i < 2; i++)
{
for (j = 0; j < 3; j++)
{
printf("%d\n", matrix[i][j]);
}
}
o/p:
1
4
2
3
6
8
Example 3:
int matrix[2][3] = { {1, 4, 2}, {3, 6, 8} };
int i, j;
for (i = 0; i < 2; i++)
{
for (j = 0; j < 3; j++)
{
printf("%d", matrix[i][j]);
}
}
o/p:
142368
Calculation of address of element of 1-D, 2-D, and 3-D using row-
major and column-major order
This article focuses on calculating the address of any element in a 1-Dimensional, 2-Dimensional, and 3-
Dimensional array in Row major order and Column major order.
Calculating the address of any element In the 1-D array:
A 1-dimensional array (or single-dimension array) is a type of linear array. Accessing its elements
involves a single subscript that can either represent a row or column index.
Example:
1-D array
To find the address of an element in an array the following formula is used-
Address of A[I] = B + W * (I – LB)
I = Subset of element whose address to be found,
B = Base address,
W = Storage size of one element store in any array(in byte),
LB = Lower Limit/Lower Bound of subscript(If not specified assume zero).
Example: Given the base address of an array A[1300 ………… 1900] as 1020 and the size of each
element is 2 bytes in the memory, find the address of A[1700].
Solution:
Given:
Base address B = 1020
Lower Limit/Lower Bound of subscript LB = 1300
Storage size of one element store in any array W = 2 Byte
Subset of element whose address to be found I = 1700
Formula used:
Address of A[I] = B + W * (I – LB)
Solution:
Address of A[1700] = 1020 + 2 * (1700 – 1300)
= 1020 + 2 * (400)
= 1020 + 800
Address of A[1700] = 1820
Calculate the address of any element in the 2-D array:
The 2-dimensional array can be defined as an array of arrays. The 2-Dimensional arrays are organized as
matrices which can be represented as the collection of rows and columns as array[M][N] where M is the
number of rows and N is the number of columns.
Example:
0 seconds of 15 secondsVolume 0%
2-D array
To find the address of any element in a 2-Dimensional array there are the following two ways-
1. Row Major Order
2. Column Major Order
1. Row Major Order:
Row major ordering assigns successive elements, moving across the rows and then down the next row, to
successive memory locations. In simple language, the elements of an array are stored in a Row-Wise
fashion.
To find the address of the element using row-major order uses the following formula:
Address of A[I][J] = B + W * ((I – LR) * N + (J – LC))
I = Row Subset of an element whose address to be found,
J = Column Subset of an element whose address to be found,
B = Base address,
W = Storage size of one element store in an array(in byte),
LR = Lower Limit of row/start row index of the matrix(If not given assume it as zero),
LC = Lower Limit of column/start column index of the matrix(If not given assume it as zero),
N = Number of column given in the matrix.
Example: Given an array, arr[1………10][1………15] with base value 100 and the size of each element
is 1 Byte in memory. Find the address of arr[8][6] with the help of row-major order.
Solution:
Given:
Base address B = 100
Storage size of one element store in any array W = 1 Bytes
Row Subset of an element whose address to be found I = 8
Column Subset of an element whose address to be found J = 6
Lower Limit of row/start row index of matrix LR = 1
Lower Limit of column/start column index of matrix = 1
Number of column given in the matrix N = Upper Bound – Lower Bound + 1
= 15 – 1 + 1
= 15
Formula:
Address of A[I][J] = B + W * ((I – LR) * N + (J – LC))
Solution:
Address of A[8][6] = 100 + 1 * ((8 – 1) * 15 + (6 – 1))
= 100 + 1 * ((7) * 15 + (5))
= 100 + 1 * (110)
Address of A[I][J] = 210
2. Column Major Order:
If elements of an array are stored in a column-major fashion means moving across the column and then to
the next column then it’s in column-major order. To find the address of the element using column-major
order use the following formula:
Address of A[I][J] = B + W * ((J – LC) * M + (I – LR))
I = Row Subset of an element whose address to be found,
J = Column Subset of an element whose address to be found,
B = Base address,
W = Storage size of one element store in any array(in byte),
LR = Lower Limit of row/start row index of matrix(If not given assume it as zero),
LC = Lower Limit of column/start column index of matrix(If not given assume it as zero),
M = Number of rows given in the matrix.
Example: Given an array arr[1………10][1………15] with a base value of 100 and the size of each
element is 1 Byte in memory find the address of arr[8][6] with the help of column-major order.
Solution:
Given:
Base address B = 100
Storage size of one element store in any array W = 1 Bytes
Row Subset of an element whose address to be found I = 8
Column Subset of an element whose address to be found J = 6
Lower Limit of row/start row index of matrix LR = 1
Lower Limit of column/start column index of matrix = 1
Number of Rows given in the matrix M = Upper Bound – Lower Bound + 1
= 10 – 1 + 1
= 10
Formula: used
Address of A[I][J] = B + W * ((J – LC) * M + (I – LR))
Address of A[8][6] = 100 + 1 * ((6 – 1) * 10 + (8 – 1))
= 100 + 1 * ((5) * 10 + (7))
= 100 + 1 * (57)
Address of A[I][J] = 157
From the above examples, it can be observed that for the same position two different address locations are
obtained that’s because in row-major order movement is done across the rows and then down to the next
row, and in column-major order, first move down to the first column and then next column. So both the
answers are right.
So it’s all based on the position of the element whose address is to be found for some cases the same
answers is also obtained with row-major order and column-major order and for some cases, different
answers are obtained.
Calculate the address of any element in the 3-D Array:
A 3-Dimensional array is a collection of 2-Dimensional arrays. It is specified by using three subscripts:
1. Block size
2. Row size
3. Column size
More dimensions in an array mean more data can be stored in that array.
Example:
3-D array
To find the address of any element in 3-Dimensional arrays there are the following two ways-
Row Major Order
Column Major Order
1. Row Major Order:
To find the address of the element using row-major order, use the following formula:
Address of A[i][j][k] = B + W *(M * N * (i-x) + N *(j-y) + (k-z))
Here:
B = Base Address (start address)
W = Weight (storage size of one element stored in the array)
M = Row (total number of rows)
N = Column (total number of columns)
P = Width (total number of cells depth-wise)
x = Lower Bound of Row
y = Lower Bound of Column
z = Lower Bound of Width
Example: Given an array, arr[1:9, -4:1, 5:10] with a base value of 400 and the size of each element is 2
Bytes in memory find the address of element arr[5][-1][8] with the help of row-major order?
Solution:
Given:
Block Subset of an element whose address to be found I = 5
Row Subset of an element whose address to be found J = -1
Column Subset of an element whose address to be found K = 8
Base address B = 400
Storage size of one element store in any array(in Byte) W = 2
Lower Limit of blocks in matrix x = 1
Lower Limit of row/start row index of matrix y = -4
Lower Limit of column/start column index of matrix z = 5
M(row) = Upper Bound – Lower Bound + 1 = 1 – (-4) + 1 = 6
N(Column)= Upper Bound – Lower Bound + 1 = 10 – 5 + 1 = 6
M and N represent the number of rows and columns in the 3D array, respectively. In the context of
address calculations for multi-dimensional arrays, these values are determined by the upper and lower
bounds of the array's dimensions.
1. **For M (rows):** M is calculated as the upper bound minus the lower bound of rows plus one.
2. **For N (columns):** N is calculated similarly, but for the columns. It is the upper bound of columns
minus the lower bound of columns plus one.
So, in the context of your array `arr[1:9, -4:1, 5:10]`, M is 6, and N is also 6. These values represent the
number of rows and columns in the array, which are crucial for address calculations in a 3D array.
Formula used:
Address of[I][J][K] =B + W (M * N(i-x) + N *(j-y) + (k-z))
Solution:
Address of arr[5][-1][8] = 400 + 2 * {[6 * 6 * (5 – 1)] + 6 * [(-1 + 4)]} + [8 – 5]
= 400 + 2 * (6*6*4)+(6*3)+3
= 400 + 2 * (165)
= 730
2. Column Major Order:
To find the address of the element using column-major order, use the following formula:1
Address of A[i][j][k]= B + W(M * N(i – x) + M *(k – z) + (j – y))
Here:
B = Base Address (start address)
W = Weight (storage size of one element stored in the array)
M = Row (total number of rows)
N = Column (total number of columns)
P = Width (total number of cells depth-wise)
x = Lower Bound of block (first subscipt)
y = Lower Bound of Row
z = Lower Bound of Column
Example: Given an array arr[1:8, -5:5, -10:5] with a base value of 400 and the size of each element is 4
Bytes in memory find the address of element arr[3][3][3] with the help of column-major order?
Solution:
Given:
Row Subset of an element whose address to be found I = 3
Column Subset of an element whose address to be found J = 3
Block Subset of an element whose address to be found K = 3
Base address B = 400
Storage size of one element store in any array(in Byte) W = 4
Lower Limit of blocks in matrix x = 1
Lower Limit of row/start row index of matrix y = -5
Lower Limit of column/start column index of matrix z = -10
M (row)= Upper Bound – Lower Bound + 1 = 5 +5 + 1 = 11
N (column)= Upper Bound – Lower Bound + 1 = 5 + 10 + 1 = 16
Formula used:
Address of[i][j][k] = B + W(M * N(i – x) + M * (j-y) + (k – z))
Solution:
Address of arr[3][3][3] = 400 + 4 * ((11*16*(3-1)+11*(3-(-5)+(3-(-10)))
= 400 + 4 * ((176*2 + 11*8 + 13)
= 400 + 4 * (453)
= 400 + 1812
= 2212
Feeling lost in the world of random DSA topics, wasting time without progress? It's time for a change!
Join our DSA course, where we'll guide you on an exciting journey to master DSA efficiently and on
schedule.
C Functions
A function is a block of code which only runs when it is called.
You can pass data, known as parameters, into a function.
Functions are used to perform certain actions, and they are important for reusing code: Define the code
once, and use it many times.
Predefined Functions
So it turns out you already know what a function is. You have been using it the whole time while studying
this tutorial!
For example, main() is a function, which is used to execute code, and printf() is a function; used to
output/print text to the screen:
Example
int main() {
printf("Hello World!");
return 0;
}
Create a Function
To create (often referred to as declare) your own function, specify the name of the function, followed by
parentheses () and curly brackets {}:
Syntax
void myFunction() {
// code to be executed
}
Example Explained
myFunction() is the name of the function
void means that the function does not have a return value. You will learn more about return values
later in the next chapter
Inside the function (the body), add code that defines what the function should do
Call a Function
Declared functions are not executed immediately. They are "saved for later use", and will be executed
when they are called.
To call a function, write the function's name followed by two parentheses () and a semicolon ;
In the following example, myFunction() is used to print a text (the action), when it is called:
Example
Inside main, call myFunction():
// Create a function
void myFunction() {
printf("I just got executed!");
}
int main() {
myFunction(); // call the function
return 0;
}
int main() {
myFunction();
myFunction();
myFunction();
return 0;
}
Syntax
returnType functionName(parameter1, parameter2, parameter3)
{
// code to be executed
}
The following function that takes a string of characters with name as parameter. When the function is
called, we pass along a name, which is used inside the function to print "Hello" and the name of each
person.
Example
void myFunction(char name[])
{
printf("Hello %s\n", name);
}
int main()
{
myFunction("Liam");
myFunction("Jenny");
myFunction("Anja");
return 0;
}
// Hello Liam
// Hello Jenny
// Hello Anja
When a parameter is passed to the function, it is called an argument. So, from the example above: name is
a parameter, while Liam, Jenny and Anja are arguments.
Multiple Parameters
Inside the function, you can add as many parameters as you want:
Example
void myFunction(char name[], int age)
{
printf("Hello %s. You are %d years old.\n", name, age);
}
int main()
{
myFunction("Liam", 3);
myFunction("Jenny", 14);
myFunction("Anja", 30);
return 0;
}
Example
void myFunction(int myNumbers[5]) {
for (int i = 0; i < 5; i++) {
printf("%d\n", myNumbers[i]);
}
}
int main() {
int myNumbers[5] = {10, 20, 30, 40, 50};
myFunction(myNumbers);
return 0;
}
Example Explained
The function (myFunction) takes an array as its parameter (int myNumbers[5]), and loops through the
array elements with the for loop.
When the function is called inside main(), we pass along the myNumbers array, which outputs the array
elements.
Note that when you call the function, you only need to use the name of the array when passing it as an
argument myFunction(myNumbers). However, the full declaration of the array is needed in the function
parameter (int myNumbers[5]).
Return Values
The void keyword, used in the previous examples, indicates that the function should not return a value. If
you want the function to return a value, you can use a data type (such as int or float, etc.) instead of void,
and use the return keyword inside the function:
Example
int myFunction(int x) {
return 5 + x;
}
int main() {
printf("Result is: %d", myFunction(3));
return 0;
}
// Outputs 8 (5 + 3)
This example returns the sum of a function with two parameters:
Example
int myFunction(int x, int y) {
return x + y;
}
int main() {
printf("Result is: %d", myFunction(5, 3));
return 0;
}
// Outputs 8 (5 + 3)
You can also store the result in a variable:
Example
int myFunction(int x, int y) {
return x + y;
}
int main() {
int result = myFunction(5, 3);
printf("Result is = %d", result);
return 0;
}
// Outputs 8 (5 + 3)
int main()
{
myFunction(); // call the function
return 0;
}
A function consist of two parts:
Declaration: the function's name, return type, and parameters (if any)
Definition: the body of the function (code to be executed)
void myFunction()
{ // declaration
// the body of the function (definition)
}
For code optimization, it is recommended to separate the declaration and the definition of the function.
You will often see C programs that have function declaration above main(), and function definition below
main(). This will make the code better organized and easier to read:
Example
// Function declaration
void myFunction();
// Function definition
void myFunction()
{
printf("I just got executed!");
}
Another Example
If we use the example from the previous regarding function parameters and return values:
Example
int myFunction(int x, int y)
{
return x + y;
}
int main() {
int result = myFunction(5, 3);
printf("Result is = %d", result);
return 0;
}
// Outputs 8 (5 + 3)
It is considered good practice to write it like this instead:
Example
// Function declaration
int myFunction(int, int);
Recursion
Recursion is the technique of making a function call itself. This technique provides a way to break
complicated problems down into simple problems which are easier to solve.
Recursion may be a bit difficult to understand. The best way to figure out how it works is to experiment
with it.
Recursion Example
Adding two numbers together is easy to do, but adding a range of numbers is more complicated. In the
following example, recursion is used to add a range of numbers together by breaking it down into the
simple task of adding two numbers:
Example
int sum(int k);
int main()
{
int result = sum(10);
printf("%d", result);
return 0;
}
int sum(int k)
{
if (k > 0) {
return k + sum(k - 1);
}
else
{
return 0;
}
}
Example Explained
When the sum() function is called, it adds parameter k to the sum of all numbers smaller than k and
returns the result. When k becomes 0, the function just returns 0. When running, the program follows
these steps:
10 + sum(9)
10 + ( 9 + sum(8) )
10 + ( 9 + ( 8 + sum(7) ) )
...
10 + 9 + 8 + 7 + 6 + 5 + 4 + 3 + 2 + 1 + sum(0)
10 + 9 + 8 + 7 + 6 + 5 + 4 + 3 + 2 + 1 + 0
Since the function does not call itself when k is 0, the program stops there and returns the result.
The developer should be very careful with recursion as it can be quite easy to slip into writing a function
which never terminates, or one that uses excess amounts of memory or processor power. However, when
written correctly recursion can be a very efficient and mathematically-elegant approach to programming.
Math Functions
There is also a list of math functions available, that allows you to perform mathematical tasks on
numbers.
To use them, you must include the math.h header file in your program:
#include <math.h>
Square Root
To find the square root of a number, use the sqrt() function:
Example
printf("%f", sqrt(16));
Round a Number
The ceil() function rounds a number upwards to its nearest integer, and the floor() method rounds a
number downwards to its nearest integer, and returns the result:
Example
printf("%f", ceil(1.4));
printf("%f", floor(1.4));
Power
The pow() function returns the value of x to the power of y (xy):
Example
printf("%f", pow(4, 3));
Function Description
Way-1
Formal parameters as a pointer −
int i;
double avg;
double sum = 0;
return avg;
}
Now, let us call the above function as follows −
#include <stdio.h>
/* function declaration */
double getAverage(int arr[], int size);
int main () {
return 0;
}
When the above code is compiled together and executed, it produces the following result −
// Driver code
int main()
{
int a = 10, b = 20;
printf("Values before swap function are: %d, %d\n",
a, b);
swap(&a, &b);
printf("Values after swap function are: %d, %d",
a, b);
return 0;
}
Output
Values before swap function are: 10, 20
Values after swap function are: 20, 10
struct student
{
int id;
char name[20];
float percentage;
};
int main()
{
struct student record;
record.id=1;
strcpy(record.name, "Raju");
record.percentage = 86.5;
func(record);
return 0;
}
#include <stdio.h>
#include <string.h>
struct student
{
int id;
char name[20];
float percentage;
};
int main()
{
struct student record;
record.id=1;
strcpy(record.name, "Raju");
record.percentage = 86.5;
func(&record);
return 0;
}
#include <stdio.h>
#include <string.h>
struct student
{
int id;
char name[20];
float percentage;
};
struct student record; // Global declaration of structure
void structure_demo();
int main()
{
record.id=1;
strcpy(record.name, "Raju");
record.percentage = 86.5;
structure_demo();
return 0;
}
void structure_demo()
{
printf(" Id is: %d \n", record.id);
printf(" Name is: %s \n", record.name);
printf(" Percentage is: %f \n", record.percentage);
}
OUTPUT:
Id is: 1
Name is: Raju
Percentage is: 86.500000
Pointers in C:
Creating Pointers
You learned from the previous chapter, that we can get the memory address of a variable with
the reference operator &:
Example
int myAge = 43; // an int variable
A pointer variable points to a data type (like int) of the same type, and is created with the *
operator.
The address of the variable you are working with is assigned to the pointer:
Example
int myAge = 43; // An int variable
int* ptr = &myAge; // A pointer variable, with the name ptr, that stores the address of myAge
Use the & operator to store the memory address of the myAge variable, and assign it to the
pointer.
Dereference
In the example above, we used the pointer variable to get the memory address of a variable
(used together with the & reference operator).
You can also get the value of the variable the pointer points to, by using the * operator (the
dereference operator):
Example
int myAge = 43; // Variable declaration
int* ptr = &myAge; // Pointer declaration
// Reference: Output the memory address of myAge with the pointer (0x7ffe5367e044)
printf("%p\n", ptr);
Notes on Pointers
Pointers are one of the things that make C stand out from other programming languages, like
Python and Java.
They are important in C, because they allow us to manipulate the data in the computer's
memory. This can reduce the code and improve the performance. If you are familiar with data
structures like lists, trees and graphs, you should know that pointers are especially useful for
implementing those. And sometimes you even have to use pointers, for example when working
with files.
But be careful; pointers must be handled with care, since it is possible to damage data stored in
other memory addresses.
Pointers & Arrays
You can also use pointers to access arrays.
Consider the following array of integers:
Example
int myNumbers[4] = {25, 50, 75, 100};
You learned from the arrays chapter that you can loop through the array elements with a for
loop:
Example
int myNumbers[4] = {25, 50, 75, 100};
int i;
Example
int myNumbers[4] = {25, 50, 75, 100};
int i;
for (i = 0; i < 4; i++) {
printf("%p\n", &myNumbers[i]);
}
Result:
0x7ffe70f9d8f0
0x7ffe70f9d8f4
0x7ffe70f9d8f8
0x7ffe70f9d8fc
Note that the last number of each of the elements' memory address is different, with an
addition of 4.
Example
// Create an int variable
int myInt;
4
So from the "memory address example" above, you can see that the compiler reserves 4 bytes
of memory for each array element, which means that the entire array takes up 16 bytes (4 * 4)
of memory storage:
Example
int myNumbers[4] = {25, 50, 75, 100};
16
How Are Pointers Related to Arrays
Ok, so what's the relationship between pointers and arrays? Well, in C, the name of an array, is
actually a pointer to the first element of the array.
Confused? Let's try to understand this better, and use our "memory address example" above
again.
The memory address of the first element is the same as the name of the array:
Example
int myNumbers[4] = {25, 50, 75, 100};
Example
int myNumbers[4] = {25, 50, 75, 100};
Example
int myNumbers[4] = {25, 50, 75, 100};
// and so on..
Result:
50
75
Or loop through it:
Example
int myNumbers[4] = {25, 50, 75, 100};
int *ptr = myNumbers;
int i;
Example
int myNumbers[4] = {25, 50, 75, 100};
This way of working with arrays might seem a bit excessive. Especially with simple arrays like in
the examples above. However, for large arrays, it can be much more efficient to access and
manipulate arrays with pointers.
It is also considered faster and easier to access two-dimensional arrays with pointers.
And since strings are actually arrays, you can also use pointers to access strings.
For now, it's great that you know how this works. But like we specified in the previous chapter;
pointers must be handled with care, since it is possible to overwrite other data stored in
memory.
Hence, there are only a few operations that are allowed to perform on Pointers in C language.
The C pointer arithmetic operations are slightly different from the ones that we generally use
for mathematical calculations. These operations are:
Increment/Decrement of a Pointer
Addition of integer to a pointer
Subtraction of integer to a pointer
Subtracting two pointers of the same type
Comparison of pointers
1. Increment/Decrement of a Pointer
Increment: It is a condition that also comes under addition. 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.
Decrement: It is a condition that also comes under subtraction. 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.
pointer increment and decrement
Note: It is assumed here that the architecture is 64-bit and all the data types are sized
accordingly. For example, integer is of 4 bytes.
#include <stdio.h>
// pointer increment and decrement
//pointers are incremented and decremented by the size of the data type they point to
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
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
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;
}
Output
p = 1441900792
p++ = 1441900796
p-- = 1441900792
q = 1441900796
q++ = 1441900800
q-- = 1441900796
r = 1441900791
r++ = 1441900792
r-- = 1441900791
Note: Pointers can be outputted using %p, since, most of the computers store the address value
in hexadecimal form using %p gives the value in that form. But for simplicity and understanding
we can also use %u to get the value in Unsigned int form.
pointer addition
// Driver Code
int main()
{
// Integer variable
int N = 4;
// Pointer to an integer
int *ptr1, *ptr2;
// Addition of 3 to ptr2
ptr2 = ptr2 + 3;
printf("Pointer ptr2 after Addition: ");
printf("%p \n", ptr2);
return 0;
}
Output
Pointer ptr2 before Addition: 0x7ffca373da9c
Pointer ptr2 after Addition: 0x7ffca373daa8
3. Subtraction of Integer to Pointer
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.
pointer substraction
// Driver Code
int main()
{
// Integer variable
int N = 4;
// Pointer to an integer
int *ptr1, *ptr2;
// Subtraction of 3 to ptr2
ptr2 = ptr2 - 3;
printf("Pointer ptr2 after Subtraction: ");
printf("%p \n", ptr2);
return 0;
}
Output
Pointer ptr2 before Subtraction: 0x7ffd718ffebc
Pointer ptr2 after Subtraction: 0x7ffd718ffeb0
4. 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.
// Driver Code
int main()
{
int x = 6; // Integer variable declaration
int N = 4;
// Pointer declaration
int *ptr1, *ptr2;
return 0;
}
Output
ptr1 = 2715594428, ptr2 = 2715594424
Subtraction of ptr1 & ptr2 is 1
5. 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.
Step 1: Initialize the integer values and point these integer values to the pointer.
Step 2: Now, check the condition by using comparison or relational operators on pointer
variables.
Step 3: Display the output.
Example of Pointer Comparision
if (ptr1 == ptr2) {
printf("Pointer to Array Name and First Element "
"are Equal.");
}
else {
printf("Pointer to Array Name and First Element "
"are not Equal.");
}
return 0;
}
Output
Pointer to Array Name and First Element are Equal.
Comparison to NULL
A pointer can be compared or assigned a NULL value irrespective of what is the pointer type.
Such pointers are called NULL pointers and are used in various pointer-related error-handling
methods.
// C Program to demonstrate the pointer comparison with NULL
// value
#include <stdio.h>
int main()
{
if (ptr == NULL) {
printf("The pointer is NULL");
}
else {
printf("The pointer is not NULL");
}
return 0;
}
Output
The pointer is NULL
Comparison operators on Pointers using an array
In the below approach, it results in the count of odd numbers and even numbers in an array. We
are going to implement this by using a pointer.
int main()
{
int n = 10; // length of an array
int arr[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
int* ptr; // Declaration of pointer variable
if (*ptr % 2 == 0) {
count_even++;
}
if (*ptr % 2 != 0) {
count_odd++;
}
ptr++; // Pointing to the next element in an array
}
printf("No of even elements in an array is : %d",
count_even);
printf("\nNo of odd elements in an array is : %d",
count_odd);
}
Output
No of even elements in an array is : 5
No of odd elements in an array is : 5
Pointer Arithmetic on Arrays
Pointers contain addresses. Adding two addresses makes no sense because there is no idea
what it would point to. Subtracting two addresses lets you compute the offset between the two
addresses. An array name acts like a pointer constant. The value of this pointer constant is the
address of the first element.
For Example: if an array is named arr then arr and &arr[0] can be used to reference the array as
a pointer.
Program 1:
// Driver Code
int main()
{
int N = 5;
// An array
int arr[] = { 1, 2, 3, 4, 5 };
int i, j;
// Driver Code
int main()
{
int N = 3, M = 2;
// A 2D array
int arr[][2] = { { 1, 2 }, { 3, 4 }, { 5, 6 } };
// Function Call
traverseArr((int*)arr, N, M);
return 0;
}
Output
12
34
56
Call By Value
In call by value method of parameter passing, the values of actual parameters are copied to the
function’s formal parameters.
// Function Prototype
void swapx(int x, int y);
// Main function
int main()
{
int a = 10, b = 20;
// Pass by Values
swapx(a, b); // Actual Parameters
printf("In the Caller:\na = %d b = %d\n", a, b);
return 0;
}
t = x;
x = y;
y = t;
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.
Example of Call by Reference
The following C program is an example of a call-by-reference method.
// Function Prototype
void swapx(int*, int*);
// Main function
int main()
{
int a = 10, b = 20;
// Pass reference
swapx(&a, &b); // Actual Parameters
return 0;
}
// Function to swap two variables
// by references
void swapx(int* x, int* y) // Formal Parameters
{
int t;
t = *x;
*x = *y;
*y = t;
Values of variables are passed by the Pointer variables are necessary to define to
Simple technique. store the address values of variables.
Note: In C, we use pointers to achieve call-by-reference. In C++, we can either use pointers
or references for pass-by-reference. In Java, primitive types are passed as values and non-
primitive types are always references.
82 84 13 78 30 3 65 22 39 47 9 42 36 68 53 74 16 73 60 8 38 79 23 61 27 2 57 58 75 37 21 70 76
43 49 19 71 41 55 18 77 14 34 32