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

Unit-IV

The document provides an overview of pointers and user-defined data types in C programming, including definitions, declarations, and initializations of pointers, as well as operations performed on them. It explains concepts such as static and dynamic memory allocation, structures, unions, and self-referential structures, with examples and syntax. Additionally, it covers memory allocation for pointers and structures, and the use of arrays of pointers and structures.

Uploaded by

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

Unit-IV

The document provides an overview of pointers and user-defined data types in C programming, including definitions, declarations, and initializations of pointers, as well as operations performed on them. It explains concepts such as static and dynamic memory allocation, structures, unions, and self-referential structures, with examples and syntax. Additionally, it covers memory allocation for pointers and structures, and the use of arrays of pointers and structures.

Uploaded by

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

52

Unit IV

Pointers & User Defined Data types

Q 1. Define a pointer. Explain how to declare and initialize a pointer.

Pointer:

A pointer is a variable which holds memory address of another variable. Pointers are powerful tools that allow direct
memory access and manipulation.

Declaring Pointer:

Declaration of pointer variable is similar to the creation of normal variable but the name is prefixed with *
symbol.

Syntax:

datatype *pointerName ;

Example:

int *ptr ;

In the above example declaration, the variable "ptr" is a pointer variable that can be used to store any integer
variable address.

Initializing a Pointer:

To assign address to a pointer variable we use assignment operator with the following syntax.

pointerVariableName = & variableName ;

Example:

int a = 50, *ptr ;

ptr = &a ;

Diagrammatic representation of above example is:

Accessing Variable Value Using Pointer

➢ Pointer variables are used to store the address of other variables.


➢ We can use this address to access the value of the variable through its pointer.
53

➢ We use the symbol "*" in front of pointer variable name to access the value of variable to which the pointer
is pointing.

Syntax:

*pointerVariableName

Example Code

#include<stdio.h>
int main()
{
int a = 10, *ptr ;
ptr = &a ;
printf("Address of variable a = %u\n", ptr) ;
printf("Value of variable a = %d\n", *ptr) ;
printf("Address of variable ptr = %u\n", &ptr) ;
return 0;
}

Output:

Address of variable a = 6487580

Value of variable a = 10

Address of variable ptr = 6487568

Q 2. How to access address of a variable?

➢ In c language, we use the reference operator "&" to access the address of variable.
➢ For example, to access the address of a variable "marks" we use "&marks".
➢ We use the following printf statement to display memory location address of variable "marks".
➢ Example:
printf("Address : %u", &marks) ;
➢ In the above example statement %u is used to display address of marks variable.
➢ Address of any memory location is unsigned integer value.

Q 3. How many bytes of memory allocated for pointer variable.

➢ Every pointer variable is used to store the address of another variable.


➢ In computer memory address of any memory location is an unsigned long integer value.
➢ In c programming language, unsigned long integer requires 4 bytes of memory.
➢ So, irrespective of pointer datatype every pointer variable is allocated with 4 bytes of memory in 32-bit
architecture.
54

Q 4. Define pointer to pointer.

➢ A pointer variable to store the address of another pointer variable is called a pointer to pointer variable.
➢ Sometimes we also call it a double pointer.

Syntax:

datatype **pointerName ;

Example:

int a;

int *p1, **p2, ***p3;

p1 = &a;

p2 = &p1;

p3 = &p2

Note:

1. To store the address of normal variable we use single pointer variable

2. To store the address of single pointer variable we use double pointer variable

3. To store the address of double pointer variable we use triple pointer variable

4. Similarly, the same for remaining pointer variables also…

Q 5. Define void pointer with example.

➢ A void pointer is a pointer variable used to store the address of a variable of any datatype.
➢ That means single void pointer can be used to store the address of integer variable, float variable, character
variable, double variable or any structure variable
➢ We use the keyword "void" to create void pointer.
Syntax:
void *pointerName ;
Example:
int a;
float b;
void *p1, *p2;
p1 = &a;
p2 = &b;
55

Q 6. What are the operations performed on pointers? Explain.


✓ Pointer variables are used to store the address of variables.
✓ Address of any variable is an unsigned integer value i.e., it is a numerical value.
✓ So, we can perform following arithmetic operations on pointer values:
1. Addition
2. Subtraction
3. Increment
4. Decrement
5. Comparison
1. Addition:
➢ 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.
➢ The addition operation on pointer variables is calculated using the following formula:
AddressAtPointer + ( NumberToBeAdd * Datatype_size )
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.

2. Subtraction:
➢ 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.
➢ The subtraction operation on pointer variables is calculated using the following formula:
AddressAtPointer - ( NumberToBeAdd * Datatype_Size )
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.
56

3. Increment:
➢ 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.
➢ The increment operation on pointer variable is calculated as follows:
AddressAtPointer + Datatype_size
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.

4. 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.
➢ The decrement operation on pointer variable is calculated as follows:
AddressAtPointer - NumberOfBytesRequiresByDatatype
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.

5. Comparison
➢ 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.
➢ The comparison operation is performing between the pointers of same datatype only.
➢ In c programming language, we can use all comparison operators (relational operators) with pointers.
57

Q 7. Describe An Array Of Pointers In C?

✓ Pointers and Array representations are very much related to each other and can be interchangeably used in
the right context.
✓ An array name is generally treated as a pointer to the first element of the array and if we store the base
address of the array in another pointer variable, then we can easily manipulate the array using pointer
arithmetic in a C Program.

Syntax

*(arr + i)

we denote array elements as arr[i], where i is the index value. Below is a similar syntax in terms of pointers of how we
can represent the array elements using the dereferencing operator (*) on the array name i.e. using the pointers
property of the array.

➔ * is a dereferencing operator used to extract the value from the address (arr + i).
➔ *(arr + i) is the same as arr[i] in a C Program.
➔ arr represents the array name and i represents the index value.

Example

#include <stdio.h>
int main()
{
// array declaration and initialization
int arr[5] = {2, 4, 6, 8, 10}, i;
for(i = 0; i < 5; i++)
{
// printing the elements address and value at
// arr[i] using *(arr + i) syntax
printf("[index %d] Address : %u, Value : %d\n", i, (arr + i), *(arr + i));
}
return 0;
}
Output :
[index 0] Address : 2364420656, Value : 2
[index 1] Address : 2364420660, Value : 4
[index 2] Address : 2364420664, Value : 6
[index 3] Address : 2364420668, Value : 8
[index 4] Address : 2364420672, Value : 10

Explanation :

We have declared and initialized an integer array arr, array representation :


58

✓ (arr + i) represents the address of the value at index i, so *(arr + i) will give the value at ith index (address(arr + i)
= address(arr[i])), it is used to print the addresses of the array elements as the value of i changes from 0-4
✓ * is a dereferencing operator used for printing the value at the provided address. *(arr + i) will print the values of
the array at consecutive addresses as the value of i changes from 0-4.
Q 8. Define static memory allocation. What are its limitations.

➢ Allocation of memory during compile time is called static memory allocation.


➢ When we declare variables memory is allocated in space called stack.
➢ The memory allocated in the stack is fixed at the time of compilation and remains until the end of the
program execution.

Limitations:

➢ When we create an array, we must specify the size at the time of the declaration itself and it cannot be
changed during the program execution.
➢ This is a major problem when we do not know the number of values to be stored in an array.

Q 9. Explain about dynamic memory allocation in C.

➢ Allocation of memory during the program execution is called dynamic memory allocation.
➢ We use pre-defined functions to allocate memory dynamically.
➢ There are FOUR pre-defined functions that are defined in the header file known as "stdlib.h".

They are as follows:

1. malloc()

2. calloc()

3. realloc()

4. free()
1. malloc():

➢ malloc() is the pre-defined function used to allocate a memory block of specified number of bytes and
returns void pointer.
➢ The void pointer can be casted to any datatype. If malloc() function unable to allocate memory due to any
reason it returns NULL pointer.

Syntax:

void* malloc(size_in_bytes)

Example:
char *title;
title = (char *) malloc(15);
59

2. calloc():
➢ calloc() is the pre-defined function used to allocate multiple memory blocks of the specified number of bytes
and initializes them to ZERO.
➢ calloc() function returns void pointer.
➢ If calloc() function unable to allocate memory due to any reason it returns a NULL pointer.
➢ Generally, calloc() is used to allocate memory for array and structure.
o calloc() function takes two arguments and they are
o The number of blocks to be allocated
➢ Size of each block in bytes
Syntax:
void* calloc(number_of_blocks, size_of_each_block_in_bytes)
Example:
int *ptr;
ptr = (int*)calloc(5, sizeof(int));
3. realloc():
➢ realloc() is the pre-defined function used to modify the size of memory blocks that were previously allocated
using malloc() or calloc().
➢ realloc() function returns void pointer.
➢ If realloc() function unable to allocate memory due to any reason it returns NULL pointer.
Syntax
void* realloc(*pointer, new_size_of_each_block_in_bytes)
Example:
char *title;
title = (char *) malloc(15);
title = (char*) realloc(title, 30);
4. free():
➢ free() is the pre-defined function used to deallocate memory block that was previously allocated using
malloc() or calloc().
Syntax
void free(*pointer)
Example:
char *title;
title = (char *) malloc(15);
free(title);
60

Q 10. Define a structure. How to declare a structure in C?


Structure:
Structure is a collection of different datatype elements which can be referred under a single name.
Creating Structure:
To create structure, we use the keyword called "struct".
Syntax:
struct structure_name
{
// Structure members
data_type member1;
data_type member2, member3;
….
};
struct structure_name structure_varaibles;
Example:
struct Student
{
// structure members
char stud_name[30];
int roll_number;
float percentage;
};
// structure variables
struct Student s1,s2;
Accessing Structure Members:
We use structure variables to access structure members with dot(.) operator.
Syntax:
Structure_varaible . structure_member
Example:
s1.stud_name
s1.roll_number
Example:
#include<stdio.h>
struct employee
{
int id;
char name[50];
}e1; //declaring e1 variable for structure
int main( )
61

{
//store first employee information
e1.id=101;
e1.name = "Ajay");
//printing first employee information
printf( "employee 1 id : %d\n", e1.id);
printf( "employee 1 name : %s\n", e1.name);
return 0;
}
Output:
employee 1 id : 101
employee 1 name : Ajay

Q 11. How much memory is allocated for a structure?


➢ The memory does not allocate on defining a structure.
➢ The memory is allocated when we create the variable of a particular structure.
➢ The size of memory allocated is equal to the sum of memory required by individual members of that
structure.

Q 12. Explain in detail about structure with arrays with example.


➢ An array of structures in C can be defined as the collection of multiple structures variables where each
variable contains information about different entities.
➢ The array of structures in C are used to store information about multiple entities of different data types.
➢ The array of structures is also known as the collection of structures.
Example:

#include<stdio.h>
struct student
{
int rollno;
62

char name[10];
};
int main()
{
int i;
struct student st[5];
printf("Enter Records of 5 students");
for(i=0;i<5;i++)
{
printf("\nEnter Rollno:");
scanf("%d",&st[i].rollno);
printf("\nEnter Name:");
scanf("%s",&st[i].name);
}
printf("\nStudent Information List:");
for(i=0;i<5;i++)
{
printf("\nRollno:%d, Name:%s",st[i].rollno,st[i].name);
}
return 0;
}
Output:
Enter Records of 5 students
Enter Rollno:1
Enter Name:Sonoo
Enter Rollno:2
Enter Name:Ratan
Enter Rollno:3
Enter Name:Vimal
Enter Rollno:4
Enter Name:James
Enter Rollno:5
Enter Name:Sarfraz
Student Information List:
Rollno:1, Name:Sonoo
Rollno:2, Name:Ratan
Rollno:3, Name:Vimal
Rollno:4, Name:James
Rollno:5, Name:Sarfraz
63

Q 13. Define self-referential structure.


• Self-Referential structures are those structures that have one or more pointers which point to the same type of
structure, as their member.

Q 14. Define union. Explain creation of union and accessing union members.
Union:
Union is a collection of different datatype elements which can be referred under a single name.
Creating Union:
To create union, we use the keyword called “union”.
Syntax:
union union_name
{
// Union members
data_type member1;
data_type member2, member3;
….
};
union union_name union_varaibles;
Example:
union Student
{
// union members
64

char stud_name[30];
int roll_number;
float percentage;
};
// union variables
union Student s1,s2;
Accessing Union Members:
We use union variables to access structure members with dot(.) operator.
Syntax:
Union_varaible . Union_member
Example:
s1.stud_name
s1.roll_number
s1.percentage
Q 15 How much memory is allocated for a Union?
➢ The memory is allocated when we create the variable of a particular union.
➢ The size of memory allocated is equal to the maximum memory required by an individual member among all
members of that union.

Q 17. Write the differences between structure and union


65

Q 18. Explain about Dangling pointer?


A pointer pointing to a memory location that has been deleted (or freed) is called dangling pointer.

You might also like