0% found this document useful (0 votes)
4 views14 pages

Unit 4

The document provides a comprehensive overview of pointers and user-defined data types in C programming. It covers the definition, declaration, initialization, and operations of pointers, including pointer to pointer and void pointers, as well as memory allocation techniques such as static and dynamic memory allocation. Additionally, it explains structures and arrays of structures, including examples and syntax for better understanding.

Uploaded by

abrarhabib75
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)
4 views14 pages

Unit 4

The document provides a comprehensive overview of pointers and user-defined data types in C programming. It covers the definition, declaration, initialization, and operations of pointers, including pointer to pointer and void pointers, as well as memory allocation techniques such as static and dynamic memory allocation. Additionally, it explains structures and arrays of structures, including examples and syntax for better understanding.

Uploaded by

abrarhabib75
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/ 14

52

Unit IV

Pointers & User Defined Data types

Q 1. Define a pointer. Explain how to declare and ini alize 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 manipula on.

Declaring Pointer:

Declara on of pointer variable is similar to the crea on of normal variable but the name is prefixed with *
symbol.

Syntax:

datatype *pointerName ;

Example:

int *ptr ;

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

Ini alizing 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 ;

Diagramma c representa on 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 poin ng.

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 prin statement to display memory loca on address of variable "marks".
 Example:
prin ("Address : %u", &marks) ;
 In the above example statement %u is used to display address of marks variable.
 Address of any memory loca on 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 loca on is an unsigned long integer value.
 In c programming language, unsigned long integer requires 4 bytes of memory.
 So, irrespec ve 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.
 Some mes 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 opera ons 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 arithme c opera ons on pointer values:
1. Addi on
2. Subtrac on
3. Increment
4. Decrement
5. Comparison
1. Addi on:
 When a pointer is added with an integer value, the value is first mul plied by the size of the data type and
then added to the pointer.
 The addi on opera on 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. Subtrac on:
 When a pointer is subtracted with an integer value, the value is first mul plied by the size of the data type
and then subtracted from the pointer similar to addi on.
 The subtrac on opera on 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 condi on that also comes under addi on. 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 opera on 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 condi on that also comes under subtrac on. 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 opera on 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 condi on and returns false for the unsa sfied condi on.
 The comparison opera on is performing between the pointers of same datatype only.
 In c programming language, we can use all comparison operators (rela onal operators) with pointers.
57

Q 7. Describe An Array Of Pointers In C?

 Pointers and Array representa ons 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
arithme c 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

Explana on :

We have declared and ini alized an integer array arr, array representa on :
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 prin ng the value at the provided address. *(arr + i) will print the values of
the array at consecu ve addresses as the value of i changes from 0-4.
Q 8. Define sta c memory alloca on. What are its limita ons.

 Alloca on of memory during compile me is called sta c memory alloca on.


 When we declare variables memory is allocated in space called stack.
 The memory allocated in the stack is fixed at the me of compila on and remains un l the end of the
program execu on.

Limita ons:

 When we create an array, we must specify the size at the me of the declara on itself and it cannot be
changed during the program execu on.
 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 alloca on in C.

 Alloca on of memory during the program execu on is called dynamic memory alloca on.
 We use pre-defined func ons to allocate memory dynamically.
 There are FOUR pre-defined func ons 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 func on 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() func on unable to allocate memory due to any
reason it returns NULL pointer.

Syntax:

void* malloc(size_in_bytes)

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

2. calloc():
 calloc() is the pre-defined func on used to allocate mul ple memory blocks of the specified number of bytes
and ini alizes them to ZERO.
 calloc() func on returns void pointer.
 If calloc() func on 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() func on 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 func on used to modify the size of memory blocks that were previously allocated
using malloc() or calloc().
 realloc() func on returns void pointer.
 If realloc() func on 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 * tle;
tle = (char *) malloc(15);
tle = (char*) realloc( tle, 30);
4. free():
 free() is the pre-defined func on used to deallocate memory block that was previously allocated using
malloc() or calloc().
Syntax
void free(*pointer)
Example:
char * tle;
tle = (char *) malloc(15);
free( tle);
60

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


Structure:
Structure is a collec on of different datatype elements which can be referred under a single name.
Crea ng 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 par cular 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 collec on of mul ple structures variables where each
variable contains informa on about different en es.
 The array of structures in C are used to store informa on about mul ple en es of different data types.
 The array of structures is also known as the collec on 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-referen al structure.


 Self-Referen al 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 crea on of union and accessing union members.
Union:
Union is a collec on of different datatype elements which can be referred under a single name.
Crea ng 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 par cular 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 poin ng to a memory loca on that has been deleted (or freed) is called dangling pointer.

You might also like