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

Unit IV Prog in C

Pointers in C store the addresses of other variables. Pointers can point to variables of any type like int, char, arrays, functions etc. Pointers are declared with a * and initialized using &. Common pointer types include null, void, and wild pointers. Pointers allow both direct and indirect variable access and are useful for memory management but must be used carefully to avoid errors.

Uploaded by

its me Lofy
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)
33 views

Unit IV Prog in C

Pointers in C store the addresses of other variables. Pointers can point to variables of any type like int, char, arrays, functions etc. Pointers are declared with a * and initialized using &. Common pointer types include null, void, and wild pointers. Pointers allow both direct and indirect variable access and are useful for memory management but must be used carefully to avoid errors.

Uploaded by

its me Lofy
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/ 29

Unit IV

Advance Programming in C

Pointer:
The pointers perform the function of storing the addresses of other variables in the
program.

These variables could be of any type- char, int, function, array, or other pointers.

The pointer sizes depend on their architecture. (For ex. the size of a pointer in the 32-bit
architecture is 2 bytes.)
Let us look at an example where we define a pointer storing an integer’s address in a
program.

int x = 10;

int* p = &x;

Here, the variable p is of pointer type, and it is pointing towards the address of the x
variable, which is of the integer type.
2

Declaration of a Pointer
Just like the variables, we also have to declare the pointers in C before we use them in
any program. We can name these pointers anything that we like, as long as they abide
by the naming rules of the C language. Normally, the declaration of a pointer would take
a form like this: data_type * name_of_pointer_variable;

Note that here,

● The data_type refers to this pointer’s base type in the variable of C. It indicates which type of
variable is the pointer pointing to in the code.
● The asterisk ( * ) is used to declare a pointer. It is an indirection operator, and it is the same
asterisk that we use in multiplication.

We can declare pointers in the C language with the use of the asterisk symbol ( * ). It is
also called the indirection pointer, as we use it for dereferencing any pointer. Here is
how we use it:

int *q; // a pointer q for int data type

char *x; // a pointer x for char data type

The Initialization of a Pointer

We use the & (ampersand) operator to get the variable’s address in the program. We
place the & just before that variable’s name whose address we require. Here is the
syntax that we use for the initialisation of a pointer,

Syntax of Pointer Initialization

pointer = &variable;
3

As we can assess in the figure shown above, the pointer variable is storing the digit
variable’s address, named fff4. This digit variable’s value is equal to 100. But aaa3 is
the pointer variable’s address (variable r).

Here, we can print the r pointer variable’s value using the indirection pointer ( * ). We will
look at an example for the same, as explained in the figure mentioned above.

#include<stdio.h>

int main(){

int digit=100;

int *r;

r=&digit; // for storing the address of the digit variable in the program

printf(“The address of the variable r is equal to %x \n”,r); // pointer r contains the digit
variable’s address, and thus, printing the variable r gives us the address of the digit.

printf(“The value of the variable r is equal to %d \n”,*r); // We are using * to dereference


the pointer, and thus, printing *r, would give the value that is stored at that address
which is contained by r.

return 0;

}
4

he output of the code mentioned above would be like this:

The address of the variable r is equal to fff4

The value of the variable r is equal to 100

Use of Pointers in C
Here is a summary of how we use the following operators for the pointers in any
program:

Operator Name Uses and Meaning of Operator

* Asterisk Declares a pointer in a program.

Returns the referenced variable’s value.

& Ampersand Returns a variable’s address

The Pointer to an Array


Here is an example to illustrate the same,

int arr [20];

int *q [20] = &arr; // The q variable of the pointer type is pointing towards the integer
array’s address or the address of arr.

The Pointer to a Function


Here is an example to illustrate the same,
5

void display (int);

void(*q)(int) = &show; // The q pointer is pointing towards the function’s address in the
program

The Pointer to a Structure


Here is an example to illustrate the same,

struct str {

int x;

float y;

}ref;

struct str *q = &ref;

void apoo()

int var = 10;


6

// declare pointer variable

int* ptr;

// data type of ptr and var must be same

ptr = &var;

// assign the address of a variable to a pointer

printf("Value at ptr = %p \n", ptr);

printf("Value at var = %d \n", var);

printf("Value at *ptr = %d \n", *ptr);

// Driver program

int main()

apoo();

return 0;

Types of Pointers
7

There are various types of pointers that we can use in the C language. Let us take a
look at the most important ones.

The Null Pointer


The null pointer has a value of 0. To create a null pointer in C, we assign the pointer
with a null value during its declaration in the program. This type of method is especially
useful when the pointer has no address assigned to it. Let us take a look at a program
that illustrates how we use the null pointer:

#include <stdio.h>

int main()

int *a = NULL; // the null pointer declaration

printf(“Value of the variable a in the program is equal to :\n%x”,a);

return 0;

The output obtained out of the program mentioned above will be:

Value of the variable a in the program is equal to: 0

The Void Pointer


The void pointer is also known as the generic pointer in the C language. This pointer
has no standard data type, and we create it with the use of the keyword void. The void
pointer is generally used for the storage of any variable’s address. Let us take a look at
a program that illustrates how we use the void pointer in a C program:
8

#include <stdio.h>

int main()

void *q = NULL; // the void pointer of the program

printf(“Size of the void pointer in the program is equal to : %d\n”,sizeof(q));

return 0;

The output obtained out of the program mentioned above will be:

Size of the void pointer in the program is equal to : 4

The Wild Pointer


We can call a pointer a wild pointer if we haven’t initialized it with anything. Such wild
pointers are not very efficient in a program, as they may ultimately point towards some
memory location that is unknown to us. It will ultimately lead to some problems in the
program, and then, it will crash. Thus, you must be very careful when using wild
pointers in a program. Let us take a look at a program that illustrates how we use the
wild pointer in a C program:

#include <stdio.h>

int main()

int *w; // the wild pointer in the program

printf(“\n%d”,*w);
9

return 0;

The output obtained out of the program mentioned above will be a compile-time error.

Here are a few more types of pointers that you can find in the C programs:

● Near pointer
● Complex pointer
● Huge pointer
● Far pointer
● Dangling pointer

Accessing Pointers- Indirectly and Directly


There are basically two ways in which a program can access a variable content and
then manipulate it:

● Direct Access: In this case, we use the variable name in the program directly.
● Indirect Access: In this case, we use some pointers to the variables in the program.

Let us take a look at a program to understand this better. Consider the below program:

#include <stdio.h>

/* Declaration and initialization of an int variable in the program */

int variable = 1;

/* Declaration of the pointer to the int variable */

int *ptr;

int main( void )

{
10

/* Initialization of ptr to the point to the variable */

ptr = &variable;

/* Accessing var indirectly and directly */

printf(“\nThe direct access of the variable would be = %d”, variable);

printf(“\nThe indirect access of the variable would be = %d”, *ptr);

/* Displaying of the address of the variable in both the ways */

printf(“\n\nOutput of the address of the variable would be = %d”, &variable);

printf(“\nOutput of the address of the variable would be = %d\n”, ptr);

/*changing of the content of the variable through the ptr pointer in the program*/

*ptr=48;

printf(“\nThe indirect access of the variable would be = %d”, *ptr);

return 0;

The compilation of this program devoid of errors would generate an output like this:

The direct access of the variable would be = 1

The indirect access of the variable would be = 1

Output of the address of the variable would be = 4202496

Output of the address of the variable would be = 4202496

The indirect access of the variable would be = 48


11

Pros of using Pointers in C


● Pointers make it easy for us to access locations of memory.
● They provide an efficient way in which we can access the elements present in the structure
of an array.
● We can use pointers for dynamic allocation and deallocation of memory.
● These are also used to create complex data structures, like the linked list, tree, graph, etc.
● It reduces the code and thus improves the overall performance. We can use it to retrieve the
strings, trees, and many more. We can also use it with structures, arrays, and functions.
● We can use the pointers for returning various values from any given function.
● One can easily access any location of memory in the computer using the pointers.

Cons of Pointers in C
● The concept of pointers is a bit tricky to understand.
● These can lead to some errors like segmentation faults, accessing of unrequired memory
locations, and many more.
● A pointer may cause corruption of memory if we provide it with an incorrect value.
● Pointers in a program can lead to leakage of memory.
● As compared to all the other variables, pointers are somewhat slower.
● Some programmers might find it very tricky to deal with pointers in a program. It is their
responsibility to use these pointers and manipulate them carefully.

Applications of Pointers in C
There are various uses of the pointers in C language. Let us look at some of them:

1. Dynamic allocation of memory: We can allocate the memory dynamically in C


language when we use the calloc() and malloc() functions. The pointers are primarily
used in such cases.

2. Structures, Functions, and Arrays: We generally use the pointers in the C language in
the cases of structures, functions, and arrays. Here, the pointers help in reducing the
code and improving the program’s performance.
12

The & Address of Operator in C


This operator basically returns the variable’s address. But keep in mind that we must
use the %u if we want to display the variable’s address.

#include<stdio.h>

int main(){

int digit=100;

printf(“The value of the digit is equal to %d and the address of the digit is equal to
%u”,digit,&digit);

return 0;

The output of the program mentioned above would be like this:

The value of the digit is equal to 100 and the address of the digit is equal to fff4

Pointer Arithmetics in C:

Pointer Arithmetic is the set of valid arithmetic operations that can be performed
on pointers.
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
13

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.
14

Example:

#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

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';
15

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;

2. Addition of Integer to Pointer


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.
16

#include <stdio.h>

// Driver Code
int main()
{
// Integer variable
int N = 4;

// Pointer to an integer
int *ptr1, *ptr2;

// Pointer stores the address of N


ptr1 = &N;
ptr2 = &N;

printf("Pointer ptr2 before Addition: ");


printf("%p \n", ptr2);

// Addition of 3 to ptr2
ptr2 = ptr2 + 3;
17

printf("Pointer ptr2 after Addition: ");


printf("%p \n", ptr2);

return 0;
}

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.
18

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.

#include <stdio.h>

int main()

int x = 6; // Integer variable declaration

int N = 4;

// Pointer declaration

int *ptr1, *ptr2;


19

ptr1 = &N; // stores address of N

ptr2 = &x; // stores address of x

printf(" ptr1 = %u, ptr2 = %u\n", ptr1, ptr2);

x = ptr2 - ptr1;

printf("Subtraction of ptr1 "

"& ptr2 is %d\n",

x);

return 0;

5. Comparison of Pointers
20

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.

#include <stdio.h>

int main()

int arr[5];

int* ptr1 = &arr;

int* ptr2 = &arr[0];

if (ptr1 == ptr2) {

printf("Pointer to Array Name and First Element "

"are Equal.");

}
21

else {

printf("Pointer to Array Name and First Element "

"are not Equal.");

return 0;

Passing Pointers to Functions in C:


Passing the pointers to the function means the memory location of the variables
is passed to the parameters in the function, and then the operations are
performed. The function definition accepts these addresses using pointers,
addresses are stored using pointers.

Arguments Passing without pointer


When we pass arguments without pointers the changes made by the function
would be done to the local variables of the function.

Below is the C program to pass arguments to function without a pointer:

#include <stdio.h>

void swap(int a, int b)


{
int temp = a;
22

a = b;
b = temp;
}

// Driver code
int main()
{
int a = 10, b = 20;
swap(a, b);
printf("Values after swap function are: %d, %d",
a, b);
return 0;
}
utput
Values after swap function are: 10, 20

Arguments Passing with pointers


A pointer to a function is passed in this example. As an argument, a pointer is
passed instead of a variable and its address is passed instead of its value. As a
result, any change made by the function using the pointer is permanently stored
at the address of the passed variable. In C, this is referred to as call by reference.

Below is the C program to pass arguments to function with pointers:

​ C
23

// C program to swap two values

// without passing pointer to

// swap function.

#include <stdio.h>

void swap(int* a, int* b)

int temp;
24

temp = *a;

*a = *b;

*b = temp;

// Driver code

int main()

{
25

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


26

Values after swap function are: 20, 10

C – Pointer to Pointer:
The pointer to a pointer in C is used when we want to store the address of
another pointer. The first pointer is used to store the address of the variable.
And the second pointer is used to store the address of the first pointer. That is
why they are also known as double-pointers. We can use a pointer to a pointer
to change the values of normal pointers or create a variable-sized 2-D array. A
double pointer occupies the same amount of space in the memory stack as a
normal pointer.

Declaration of Pointer to a Pointer in C


Declaring Pointer to Pointer is similar to declaring a pointer in C. The difference
is we have to place an additional ‘*’ before the name of the pointer.

data_type_of_pointer **name_of_variable = &


normal_pointer_variable;

int val = 5;

int *ptr = &val; // storing address of val to pointer ptr.

int **d_ptr = &ptr; // pointer to a pointer declared


27

// which is pointing to an integer.

The first pointer ptr1 stores the address of the variable and the second pointer
ptr2 stores the address of the first pointer.

#include <stdio.h>

int main()

int var = 789;

// pointer for var

int* ptr2;

// double pointer for ptr2

int** ptr1;

// storing address of var in ptr2

ptr2 = &var;

// Storing address of ptr2 in ptr1

ptr1 = &ptr2;

// Displaying value of var using

// both single and double pointers


28

printf("Value of var = %d\n", var);

printf("Value of var using single pointer = %d\n", *ptr2);

printf("Value of var using double pointer = %d\n", **ptr1);

return 0;

Application of Double Pointers in C


Following are the main uses of pointer to pointers in C:

● They are used in the dynamic memory allocation of multidimensional


arrays.
29

● They can be used to store multilevel data such as the text document
paragraph, sentences, and word semantics.
● They are used in data structures to directly manipulate the address of
the nodes without copying.
● They can be used as function arguments to manipulate the address
stored in the local pointer.

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy