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

unit4_C (1)

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views

unit4_C (1)

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 29

UNIT 4 : ARRAY AND POINTERS

1. Write a short note on Pointers.


Answer :
● The pointer in C language is a variable which stores the address of another
variable.
● This variable can be of type int, char, array,etc.
● we can get the memory address of a variable with the reference operator &
● syntax:
datatype *pointer_name;
● Declaring a pointer
The pointer in c language can be declared using * (asterisk symbol). It is also known
as an indirection pointer used to dereference a pointer.
int *a;//pointer to int
char *c;//pointer to char

●Example
#include <stdio.h>
int main () {
int var = 20; /* actual variable declaration */
int *ip; /* pointer variable declaration */
ip = &var; /* store address of var in pointer variable*/
printf("variable: %d", var);
printf("Address of var variable: %p", &var);
/* address stored in pointer variable */
printf("Address stored in ip variable: %p\n", ip );
/* access the value using the pointer */
printf("Value of *ip variable: %d\n", *ip );
return 0;
}
When the above code is compiled and executed, it produces the following result −
variable : 20
Address of var variable: bffd8b3c
Address stored in ip variable: bffd8b3c
Value of *ip variable: 20

● A pointer that is assigned NULL is called a null pointer.


#include <stdio.h>
int main () {
int *ptr = NULL;
printf("The value of ptr is : %p\n", ptr );
return 0;
}
o/p:The value of ptr is 0
2. Explain the concept of array in detail.
Answer :
● 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};
We have now created a variable that holds an array of four integers.
● To access an array element, refer to its index number.
● Array indexes start with 0: [0] is the first element. [1] is the second element, etc.
● This statement accesses the value of the first element [0] in myNumbers:
Example
int myNumbers[] = {25, 50, 75, 100};
printf("%d", myNumbers[0]);
// Outputs 25
● Change an Array Element
To change the value of a specific element, refer to the index number:
Example
myNumbers[0] = 33;
Example
int myNumbers[] = {25, 50, 75, 100};
myNumbers[0] = 33;
printf("%d", myNumbers[0]);
// Now outputs 33 instead of 25

● Loop Through an Array :


You can loop through the array elements with the for loop.
The following example outputs all elements in the myNumbers array:
Example
int myNumbers[] = {25, 50, 75, 100};
for (int i = 0; i < 4; i++) {
printf("%d\n", myNumbers[i]);
}
● Set Array Size
Another common way to create arrays, is to specify the size of the array, and add
elements later:
Example
// Declare an array of four integers:
int myNumbers[4];
// 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.

3. Differentiate between Pointer and Array


Answer :

SR.NO POINTERS ARRAYS


1 The pointer in C language is a variable An array is defined as
which stores the address of another the collection of similar
variable types of data items
stored at contiguous(one
after the another)
memory locations.
2 Syntax: Syntax:
datatype *pointer_name; array_name[array_size ];

3 It refers address of the variable It refers directly to the


elements.

4 Memory allocation is in random. Memory allocation is in


sequence.
5 Meant for dynamic memory allocation Help to allocate
fixed-size memory
6 Example:
Example: int array[4]={1,15,14,18}
int a=10;
int *ptr=&a;

4. Write a short note on types of array


Answer :
● Arrays are used to store multiple values in a single variable, instead of declaring
separate variables for each value.
● We can declare an array in C as
int arr[50];
Where arr is an array which can hold 50 elements of integer types.
● Arrays are classified into two types in C language:
1. Single dimensional array or 1d array.
2. Multidimensional array, eg - two-dimensional array in C.
● Single dimensional arrays:
❖ To declare an array in C, a programmer specifies the type of the elements
and the number of elements required by an array as follows −
type arrayName [ arraySize ];
❖ This is called a single-dimensional array. The arraySize must be an
integer constant greater than zero and type can be any valid C data type.
For example, to declare a 10-element array called balance of type double,
use this statement −
double balance[10];

❖ Here balance is a variable array which is sufficient to hold up to 10


double numbers.
❖ Initializing Arrays
❖ You can initialize an array in C either one by one or using a single
statement as follows −
❖ double balance[5] = {1000.0, 2.0, 3.4, 7.0, 50.0};

❖ The number of values between braces { } cannot be larger than the


number of elements that we declare for the array between square
brackets [ ].
❖ Accessing Array Elements
An element is accessed by indexing the array name. This is done by placing the index
of the element within square brackets after the name of the array. For example −
double salary = balance[9];
The above statement will take the 10th element from the array and assign
the value to the salary variable.

2. Multi Dimensional Array


● An array of arrays is called as multi dimensional array. In simple words, an
array created with more than one dimension (size) is called as multi
dimensional array. Multi dimensional array can be of two dimensional array or
three dimensional array or four dimensional array or more…
● Two Dimensional Arrays can be thought of as an array of arrays, or as a matrix
consisting of rows and columns.
● The 2-D arrays are used to store data in the form of table.
● We also use 2-D arrays to create mathematical matrices.
Declaration of Two Dimensional Array
We use the following general syntax for declaring a two dimensional array...
datatype arrayName [ rowSize ] [ columnSize ] ;

Example Code
int matrix_A [2][3] ;

The above declaration of two dimensional array reserves 6 continuous memory


locations of 2 bytes each in the form of 2 rows and 3 columns.
Initialization of Two Dimensional Array
We use the following general syntax for declaring and initializing a two dimensional
array with a specific number of rows and columns with initial values.
datatype arrayName [rows][colmns] = {{r1c1value, r1c2value, ...},{r2c1, r2c2,...}...} ;

Example Code
int matrix_A [2][3] = { {1, 2, 3},{4, 5, 6} } ;

The above declaration of two-dimensional array reserves 6 contiguous memory


locations of 2 bytes each in the form of 2 rows and 3 columns. And the first row is
initialized with values 1, 2 & 3 and the second row is initialized with values 4, 5 & 6.

We can also initialize as follows...

Example Code
int matrix_A [2][3] = {
{1, 2, 3},
{4, 5, 6}
};

Accessing Individual Elements of Two Dimensional Array


In a c programming language, to access elements of a two-dimensional array we use
array name followed by row index value and column index value of the element that to
be accessed. Here the row and column index values must be enclosed in separate
square braces. In case of the two-dimensional array the compiler assigns separate
index values for rows and columns.

We use the following general syntax to access the individual elements of a


two-dimensional array...
arrayName [ rowIndex ] [ columnIndex ]

Example Code
matrix_A [0][1] = 10 ;

In the above statement, the element with row index 0 and column index 1 of matrix_A
array is assigned with value 10.

5. Explain Single dimensional array in detail?


Answer :
● Single dimensional arrays:
❖ To declare an array in C, a programmer specifies the type of the elements
and the number of elements required by an array as follows −
type arrayName [ arraySize ];
❖ This is called a single-dimensional array. The arraySize must be an
integer constant greater than zero and type can be any valid C data type.
For example, to declare a 10-element array called balance of type double,
use this statement −
double balance[10];
❖ Here balance is a variable array which is sufficient to hold up to 10
double numbers.
❖ Initializing Arrays
❖ You can initialize an array in C either one by one or using a single
statement as follows −
❖ double balance[5] = {1000.0, 2.0, 3.4, 7.0, 50.0};

❖ The number of values between braces { } cannot be larger than the


number of elements that we declare for the array between square
brackets [ ].
❖ Accessing Array Elements
An element is accessed by indexing the array name. This is done by placing the index
of the element within square brackets after the name of the array. For example −
double salary = balance[9];
The above statement will take the 10th element from the array and assign
the value to the salary variable.
6. Explain Multi-dimensional array in detail?
Answer :
Multi Dimensional Array
● An array of arrays is called as multi dimensional array. In simple words, an
array created with more than one dimension (size) is called as multi
dimensional array. Multi dimensional array can be of two dimensional array or
three dimensional array or four dimensional array or more…
● Two Dimensional Arrays can be thought of as an array of arrays, or as a matrix
consisting of rows and columns.
● The 2-D arrays are used to store data in the form of table.
● We also use 2-D arrays to create mathematical matrices.
Declaration of Two Dimensional Array
We use the following general syntax for declaring a two dimensional array...
datatype arrayName [ rowSize ] [ columnSize ] ;

Example Code
int matrix_A [2][3] ;
The above declaration of two dimensional array reserves 6 continuous memory
locations of 2 bytes each in the form of 2 rows and 3 columns.
Initialization of Two Dimensional Array
We use the following general syntax for declaring and initializing a two dimensional
array with a specific number of rows and columns with initial values.
datatype arrayName [rows][colmns] = {{r1c1value, r1c2value, ...},{r2c1, r2c2,...}...} ;

Example Code
int matrix_A [2][3] = { {1, 2, 3},{4, 5, 6} } ;

The above declaration of two-dimensional array reserves 6 contiguous memory


locations of 2 bytes each in the form of 2 rows and 3 columns. And the first row is
initialized with values 1, 2 & 3 and the second row is initialized with values 4, 5 & 6.

We can also initialize as follows...

Example Code
int matrix_A [2][3] = {
{1, 2, 3},
{4, 5, 6}
};

Accessing Individual Elements of Two Dimensional Array


In a c programming language, to access elements of a two-dimensional array we use
array name followed by row index value and column index value of the element that to
be accessed. Here the row and column index values must be enclosed in separate
square braces. In case of the two-dimensional array the compiler assigns separate
index values for rows and columns.

We use the following general syntax to access the individual elements of a


two-dimensional array...
arrayName [ rowIndex ] [ columnIndex ]

Example Code
matrix_A [0][1] = 10 ;

In the above statement, the element with row index 0 and column index 1 of matrix_A
array is assigned with value 10.

7. Explain advantages and disadvantages of Arrays


Answer:
Advantage of Array:
1) Code Optimization: Data can be accessed by very less code.
2) Ease of traversing: Traversing of an Array is very easy with a for loop.
3) Ease of sorting: We can easily sort Array elements.
4) Random Access: Also we can access elements randomly.
5) Data Structure Implementation: Array helps to implement various data structures
like linked lists, stack, queue, trees, graphs, etc.
6) Matrix Representation: With the help of 2 Array, Matrix can be represented.
Disadvantage of Array:
1). Time complexity: In insertion and deletion operation, Time complexity increases.
2). Memory Wastage: Because arrays are fixed in size so if no elements in an array,
still it consumes all spaces.
3). Fixed In Size: Once you had declared the size of an array, it is not possible to
increase it.

8. Explain pointers and addresses in C?


Answer :
● C Pointers:
● Pointers (pointer variables) are special variables that are used to store
addresses rather than values.
● Pointer Syntax
Here is how we can declare pointers.
int* p;
Here, we have declared a pointer p of int type.
● Address in C:
● If you have a variable var in your program, &var will give you its address
in the memory.
● We have used address numerous times while using the scanf() function.
scanf("%d", &var);
● Here, the value entered by the user is stored in the address of var variable. Let's
take a working example.
#include <stdio.h>
int main()
{
int var = 5;
printf("var: %d\n", var);
// Notice the use of & before var
printf("address of var: %p", &var);
return 0;
}

Output
var: 5
address of var: 2686778
Note: You will probably get a different address when you run the above code.

9. Explain pointers and function arguments in C?


Answer :
● Pointer as a function parameter is used to hold addresses of arguments passed
during function call. This is also known as call by reference.
● When a function is called by reference any change made to the reference
variable will affect the original variable.
● Example:
#include <stdio.h>
void swap(int *a, int *b);
int main()
{
int m = 10, n = 20;
printf("m = %d\n", m);
printf("n = %d\n\n", n);
swap(&m, &n); //passing address of m and n to the swap function
printf("After Swapping:\n\n");
printf("m = %d\n", m);
printf("n = %d", n);
return 0;
}
/*
pointer 'a' and 'b' holds and
points to the address of 'm' and 'n'
*/
void swap(int *a, int *b)
{
int temp;
temp = *a;
*a = *b;
*b = temp;
}

Output:
m = 10 n = 20 After Swapping: m = 20 n = 10

10. Short note on command line arguments?


Answer :
● It is possible to pass some values from the command line to your C programs
when they are executed.
● These values are called command line arguments and many times they are
important for your program especially when you want to control your program
from outside instead of hard coding those values inside the code.
● The command line arguments are handled using main() function arguments
where argc refers to the number of arguments passed, and argv[] is a pointer
array which points to each argument passed to the program.
● Following is a simple example which checks if there is any argument supplied
from the command line and take action accordingly −
#include <stdio.h>
int main( int argc, char *argv[] ) {
if( argc == 2 ) {
printf("The argument supplied is %s\n", argv[1]);
}
else if( argc > 2 ) {
printf("Too many arguments supplied.\n");
}
else {
printf("One argument expected.\n");
}
}
When the above code is compiled and executed with a single argument, it produces the
following result.
$./a.out testing
The argument supplied is testing
When the above code is compiled and executed with two arguments, it produces the
following result.
$./a.out testing1 testing2
Too many arguments supplied.
When the above code is compiled and executed without passing any argument, it
produces the following result.
$./a.out
One argument expected
● It should be noted that argv[0] holds the name of the program itself and argv[1]
is a pointer to the first command line argument supplied, and *argv[n] is the
last argument. If no arguments are supplied, argc will be one, and if you pass
one argument then argc is set at 2.
● You pass all the command line arguments separated by a space, but if the
argument itself has a space then you can pass one argument then argc is set at
2.
● You pass all the command line arguments separated by a space, but if the
argument itself has a space then you can pass such arguments by putting them
inside double quotes "" or single quotes ''.
● Let us re-write above example once again where we will print program name
and we also pass a command line argument by putting inside double quotes −
#include <stdio.h>
int main( int argc, char *argv[] ) {
printf("Program name %s\n", argv[0]);
if( argc == 2 ) {
printf("The argument supplied is %s\n", argv[1]);
}
else if( argc > 2 ) {
printf("Too many arguments supplied.\n");
}
else {
printf("One argument expected.\n");
}
}
When the above code is compiled and executed with a single argument separated by
space but inside double quotes, it produces the following result.
$./a.out "testing1 testing2"
Program name ./a.out
The argument supplied is testing1 testing2
11. Short note on Dynamic memory allocation in C?
Answer:
● The concept of dynamic memory allocation in c language enables the
C programmer to allocate memory at runtime.
● Dynamic memory allocation in c language is possible by 4 functions of
the stdlib.h header file.
1. malloc()
2. calloc()
3. realloc()
4. free()
C malloc()
The name "malloc" stands for memory allocation.
The malloc() function reserves a block of memory of the specified number of bytes.
And, it returns a pointer of void which can be casted into pointers of any form.

Syntax of malloc()
ptr = (castType*) malloc(size);
Example
ptr = (float*) malloc(100 * sizeof(float));
The above statement allocates 400 bytes of memory. It's because the size of float is 4
bytes. And, the pointer ptr holds the address of the first byte in the allocated memory.
The expression results in a NULL pointer if the memory cannot be allocated.

C calloc()
The name "calloc" stands for contiguous allocation.
The malloc() function allocates memory and leaves the memory uninitialized, whereas
the calloc() function allocates memory and initializes all bits to zero.

Syntax of calloc()
ptr = (castType*)calloc(n, size);
Example:
ptr = (float*) calloc(25, sizeof(float));
The above statement allocates contiguous space in memory for 25 elements of type
float.

C free()
Dynamically allocated memory created with either calloc() or malloc() doesn't get freed
on their own. You must explicitly use free() to release the space.

Syntax of free()
free(ptr);
This statement frees the space allocated in the memory pointed by ptr.

C realloc()
If the dynamically allocated memory is insufficient or more than required, you can
change the size of previously allocated memory using the realloc() function.

Syntax of realloc()
ptr = realloc(ptr, x);
Here, ptr is reallocated with a new size x.

12. Explain malloc() and free() in detail


Answer :
An array is a collection of a fixed number of values. Once the size of an array is
declared, you cannot change it.
Sometimes the size of the array you declared may be insufficient. To solve this issue,
you can allocate memory manually during run-time. This is known as dynamic
memory allocation in C programming.
To allocate memory dynamically, library functions are malloc(), calloc(), realloc() and
free() are used. These functions are defined in the <stdlib.h> header file.
C malloc()
The name "malloc" stands for memory allocation.
The malloc() function reserves a block of memory of the specified number of bytes.
And, it returns a pointer of void which can be casted into pointers of any form.
Syntax of malloc()
ptr = (castType*) malloc(size);
Example
ptr = (float*) malloc(100 * sizeof(float));
The above statement allocates 400 bytes of memory. It's because the size of float is 4
bytes. And, the pointer ptr holds the address of the first byte in the allocated memory.
The expression results in a NULL pointer if the memory cannot be allocated.
C free()
Dynamically allocated memory created with either calloc() or malloc() doesn't get freed
on their own. You must explicitly use free() to release the space.
Syntax of free()
free(ptr);
This statement frees the space allocated in the memory pointed by ptr.
Example 1: malloc() and free()
// Program to calculate the sum of n numbers entered by the user
#include <stdio.h>
#include <stdlib.h>
int main() {
int n, i, *ptr, sum = 0;
printf("Enter number of elements: ");
scanf("%d", &n);
ptr = (int*) malloc(n * sizeof(int));
// if memory cannot be allocated
if(ptr == NULL) {
printf("Error! memory not allocated.");
exit(0);
}
printf("Enter elements: ");
for(i = 0; i < n; ++i) {
scanf("%d", ptr + i);
sum += *(ptr + i);
}
printf("Sum = %d", sum);
// deallocating the memory
free(ptr);
return 0;
}
Output
Enter number of elements: 3
Enter elements: 100
20
36
Sum = 156

13. Explain calloc() and free() in detail


Answer :
C calloc()
The name "calloc" stands for contiguous allocation.
The malloc() function allocates memory and leaves the memory uninitialized, whereas
the calloc() function allocates memory and initializes all bits to zero.
Syntax of calloc()
ptr = (castType*)calloc(n, size);
Example:
ptr = (float*) calloc(25, sizeof(float));
The above statement allocates contiguous space in memory for 25 elements of type
float.
C free()
Dynamically allocated memory created with either calloc() or malloc() doesn't get freed
on their own. You must explicitly use free() to release the space.
Syntax of free()
free(ptr);
This statement frees the space allocated in the memory pointed by ptr.
Here, we have dynamically allocated the memory for n number of int.
Example 2: calloc() and free()
// Program to calculate the sum of n numbers entered by the user
#include <stdio.h>
#include <stdlib.h>
int main() {
int n, i, *ptr, sum = 0;
printf("Enter number of elements: ");
scanf("%d", &n);
ptr = (int*) calloc(n, sizeof(int));
if(ptr == NULL) {
printf("Error! memory not allocated.");
exit(0);
}
printf("Enter elements: ");
for(i = 0; i < n; ++i) {
scanf("%d", ptr + i);
sum += *(ptr + i);
}
printf("Sum = %d", sum);
free(ptr);
return 0;
}
Run Code
Output
Enter number of elements: 3
Enter elements: 100
20
36
Sum = 156
14. Explain realloc() with an example?
Answer:
C realloc()
If the dynamically allocated memory is insufficient or more than required, you can
change the size of previously allocated memory using the realloc() function.

Syntax of realloc()
ptr = realloc(ptr, x);
Here, ptr is reallocated with a new size x.

Example 3: realloc()
#include <stdio.h>
#include <stdlib.h>
int main() {
int *ptr, i , n1, n2;
printf("Enter size: ");
scanf("%d", &n1);
ptr = (int*) malloc(n1 * sizeof(int));
printf("Addresses of previously allocated memory:\n");
for(i = 0; i < n1; ++i)
printf("%pc\n",ptr + i);
printf("\nEnter the new size: ");
scanf("%d", &n2);
// rellocating the memory
ptr = realloc(ptr, n2 * sizeof(int));
printf("Addresses of newly allocated memory:\n");
for(i = 0; i < n2; ++i)
printf("%pc\n", ptr + i);
free(ptr);
return 0;
}
Output
Enter size: 2
Addresses of previously allocated memory:
26855472
26855476
Enter the new size: 4
Addresses of newly allocated memory:
26855472
26855476
26855480
26855484
15. Explain Pointers to function?
Answer :
Pointer to functions
It is possible to declare a pointer pointing to a function which can then be used as an
argument in another function. A pointer to a function is declared as follows,
type (*pointer-name)(parameter);
Here is an example :
int (*sum)(); //legal declaration of pointer to function
int *sum(); //This is not a declaration of pointer to function
A function pointer can point to a specific function when it is assigned the name of that
function.
int sum(int, int);
int (*s)(int, int);
s = sum;
Here s is a pointer to a function sum. Now sum can be called using function pointer s
along with providing the required argument values.
s (10, 20);
Example of Pointer to Function
#include <stdio.h>
int sum(int x, int y)
{
return x+y;
}
int main( )
{
int (*fp)(int, int);
fp = sum;
int s = fp(10, 15);
printf("Sum is %d", s);
return 0;
}
output:
25
16. Explain Pointer Arrays in detail?
Answer :
There may be a situation when we want to maintain an array, which can store
pointers to an int or char or any other data type available. Following is the declaration
of an array of pointers to an integer −
int *ptr[MAX];
It declares ptr as an array of MAX integer pointers. Thus, each element in ptr, holds a
pointer to an int value. The following example uses three integers, which are stored in
an array of pointers, as follows −
#include <stdio.h>
const int MAX = 3;
int main () {
int var[] = {10, 100, 200};
int i, *ptr[MAX];
for ( i = 0; i < MAX; i++) {
ptr[i] = &var[i]; /* assign the address of integer. */
}
for ( i = 0; i < MAX; i++) {
printf("Value of var[%d] = %d\n", i, *ptr[i] );
}
return 0;
}
When the above code is compiled and executed, it produces the following result −
Value of var[0] = 10
Value of var[1] = 100
Value of var[2] = 200

17. Explain Character Pointer in C?


Answer:
Declaration: char *pointer;
Example: char *ptr;
Initialization:
Before use, every pointer must be initialized. To initialize a pointer, we assign it the
address of a string.
Syntax: pointer = stringname;
Example:
char str[20] = “Hello”;
char *ptr;
ptr=str;
strings and pointers in c
Using the pointer, string characters can be accessed and modified. Each character can
be accessed using *ptr. For example, to display all characters using pointer, the
following loop is used:
char str[20] = “Hello”, *ptr;
for(ptr=str; *ptr!=’\0′; ptr++)
putchar(*ptr);
Example 2:
char arr[] = “Hello World”; // Array Version
char ptr* = “Hello World”; // Pointer Version
Example 3:
#include<stdio.h>
#include<string.h>
int main ()
{
char str[10];
char *ptr;
printf ("enter a character:\n");
gets (str);
puts (str);
ptr = str;
printf ("name = %c", *ptr);
}
18.Explain Pointers arithmetic in C?
We can perform arithmetic operations on the pointers like addition, subtraction, etc.
However, as we know that pointer contains the address, the result of an arithmetic
operation performed on the pointer will also be a pointer if the other operand is of type
integer. In pointer-from-pointer subtraction, the result will be an integer value.
Following arithmetic operations are possible on the pointer in C language:
o Increment
o Decrement
o Addition
o Subtraction
o Comparison

Incrementing Pointer in C
If we increment a pointer by 1, the pointer will start pointing to the immediate next
location. This is somewhat different from the general arithmetic since the value of the
pointer will get increased by the size of the data type to which the pointer is pointing.
32-bit
For 32-bit int variable, it will be incremented by 2 bytes.
64-bit
For 64-bit int variable, it will be incremented by 4 bytes.
Let's see the example of incrementing pointer variable on 64-bit architecture.
#include<stdio.h>
int main()
{
int number=50;
int *p; //pointer to int
p=&number; //stores the address of number variable
printf("Address in p variable is %u \n",p);
p=p+1;
printf("After increment: Address of p variable is %u \n",p); // in our case, p will get incre
mented by 4 bytes.
return 0;
}

Output
Address of p variable is 3214864300
After increment: Address of p variable is 3214864304
Decrementing Pointer in C
Like increment, we can decrement a pointer variable. If we decrement a pointer, it will
start pointing to the previous location. The formula of decrementing the pointer is
given below:
32-bit
For 32-bit int variable, it will be decremented by 2 bytes.
64-bit
For 64-bit int variable, it will be decremented by 4 bytes.
Let's see the example of decrementing pointer variable on 64-bit OS.
#include <stdio.h>
void main(){
int number=50;
int *p;//pointer to int
p=&number;//stores the address of number variable
printf("Address of p variable is %u \n",p);
p=p-1;
printf("After decrement: Address of p variable is %u \n",p); // P will now point to the imm
idiate previous location.
}
Output
Address of p variable is 3214864300
After decrement: Address of p variable is 3214864296
C Pointer Addition
We can add a value to the pointer variable. The formula of adding value to pointer is
given below:
32-bit
For 32-bit int variable, it will add 2 * number.
64-bit
For 64-bit int variable, it will add 4 * number.
Let's see the example of adding value to pointer variable on 64-bit architecture.
#include<stdio.h>
int main()
{
int number=50;
int *p;//pointer to int
p=&number;//stores the address of number variable
printf("Address of p variable is %u \n",p);
p=p+3; //adding 3 to pointer variable
printf("After adding 3: Address of p variable is %u \n",p);
return 0;
}
Output
Address of p variable is 3214864300
After adding 3: Address of p variable is 3214864312
As you can see, the address of p is 3214864300. But after adding 3 with p variable, it
is 3214864312, i.e., 4*3=12 increment. Since we are using 64-bit architecture, it
increments 12. But if we were using 32-bit architecture, it was incrementing to 6 only,
i.e., 2*3=6. As integer value occupies 2-byte memory in 32-bit OS.
C Pointer Subtraction
Like pointer addition, we can subtract a value from the pointer variable. Subtracting
any number from a pointer will give an address. The formula of subtracting value from
the pointer variable is given below:
32-bit
For 32-bit int variable, it will subtract 2 * number.
64-bit
For 64-bit int variable, it will subtract 4 * number.
Let's see the example of subtracting value from the pointer variable on 64-bit
architecture.
#include<stdio.h>
int main(){
int number=50;
int *p;//pointer to int
p=&number;//stores the address of number variable
printf("Address of p variable is %u \n",p);
p=p-3; //subtracting 3 from pointer variable
printf("After subtracting 3: Address of p variable is %u \n",p);
return 0;
}
Output
Address of p variable is 3214864300
After subtracting 3: Address of p variable is 3214864288
You can see after subtracting 3 from the pointer variable, it is 12 (4*3) less than the
previous address value.
Comparison 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.
#include <stdio.h>
int main() {
// code
int num1=5,num2=6,num3=5; //integer input
int *p1=&num1;// addressing the integer input to
pointer
int *p2=&num2;
int *p3=&num3;
//comparing the pointer variables.
if(*p1<*p2)
{
printf("\n%d less than %d",*p1,*p2);
}
if(*p2>*p1)
{
printf("\n%d greater than %d",*p2,*p1);
}
if(*p3==*p1)
{
printf("\nBoth the values are equal");
}
if(*p3!=*p2)
{
printf("\nBoth the values are not equal");
}

return 0;
}
Output
5 less than 6
6 greater than 5
Both the values are equal
Both the values are not equal
19. What are various Arithmetic pointers?Explain C pointer Addition in detail?
20. What are various Arithmetic pointers?Explain C pointer subtraction in detail?
21. What are various Arithmetic pointers?Explain C pointer increment in detail?
22. What are various Arithmetic pointers?Explain C pointer decrement in detail?
23.What are various Arithmetic pointers?Explain C pointer comparison in detail?
24.Differentiate between one-dimensional and two-dimensional arrays?

Sr.no One-dimensional array Two-dimensional array


1 A one-dimensional array stores a A two-dimensional array stores an
single list of various elements array of various arrays, or a list of
having a similar data type. various lists, or an array of
various one-dimensional arrays.
2 It represents multiple data items in It represents multiple data items
the form of a list. in the form of a table that
contains columns and rows.
3 It has only one dimension. It has a total of two dimensions.
4 Syntax : datatype Syntax:
variable_name[row] datatype
variable_name[row][column]
5 Example : Example:
int arr[2][5]; //an array with two
int arr[5]; //an array with one row rows and five columns will be
and five columns will be created. created.

You might also like