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

Unit 2 OOPS

The document provides an overview of pointers in C, including their definition, declaration, initialization, and arithmetic operations. It also compares arrays and structures, discusses dynamic memory allocation, and explains how pointers relate to 2D arrays. Additionally, it includes code examples for printing employee details using structures and swapping values of two numbers using pointers.

Uploaded by

kambletathagat2
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)
11 views

Unit 2 OOPS

The document provides an overview of pointers in C, including their definition, declaration, initialization, and arithmetic operations. It also compares arrays and structures, discusses dynamic memory allocation, and explains how pointers relate to 2D arrays. Additionally, it includes code examples for printing employee details using structures and swapping values of two numbers using pointers.

Uploaded by

kambletathagat2
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/ 9

Unit 2

Q. Define pointer. How is It declared and initialized?


What are different arithmetic operations that can be
used with pointers?
Pointer in C

In C programming, a pointer is a variable that stores the memory address of another variable.
It allows direct manipulation of memory and facilitates dynamic memory allocation. Pointers
are widely used in C for tasks such as dynamic memory allocation, passing arguments to
functions by reference, and building complex data structures like linked lists and trees.

Declaration and Initialization of Pointers

A pointer is declared by specifying the data type it points to, followed by an asterisk (*) and
the pointer’s name. For example:

int *ptr; // declares a pointer to an integer

To initialize a pointer, it can be assigned the address of another variable using the address-of
operator (&) or by assigning it to NULL.

int num = 10;


int *ptr = # // initializes ptr with the address of num
int *ptr = NULL; // initializes ptr with NULL

Arithmetic Operations with Pointers

In C, pointers support several arithmetic operations, which allow for navigation through
memory locations and manipulation of data. The following arithmetic operations can be
performed on pointers:

1. Increment and Decrement: Pointers can be incremented or decremented to move to the


next or previous memory location of the pointed data type.

ptr++; // moves ptr to the next memory location of its data type
ptr--; // moves ptr to the previous memory location of its data type

2. Addition and Subtraction: Pointers can be added or subtracted with an integer value,
which results in moving the pointer by a specific number of elements of its data type.

ptr = ptr + 3; // moves ptr three elements forward from its current
position
ptr = ptr - 2; // moves ptr two elements backward from its current
position

3. Pointer Difference: Subtracting two pointers pointing to elements of the same array
gives the number of elements between them.

int arr[5];
int *ptr1 = &arr[0];
Unit 2
int *ptr2 = &arr[3];
int diff = ptr2 - ptr1; // diff will be 3, as there are three
elements between ptr1 and ptr2

4. Comparison: Pointers can be compared using relational operators (<, >, <=, >=) to
determine their relative positions in memory.

It’s important to note that arithmetic operations on pointers should be used with caution to
avoid accessing invalid memory locations or causing undefined behavior.

Q. What is the difference between Array and Structure?


Array Structure

An array is a data structure that stores a A structure is a user-defined data type that
fixed-size sequence of elements of the groups together related data items of
same type. different types.

The elements in an array are stored in The elements in a structure are stored in
contiguous memory locations. separate memory locations.

Array elements can be accessed using an Structure members can be accessed using
index value. dot notation.

Arrays have a fixed size, which is Structures can have different sizes,
determined at the time of declaration. depending on the size of their members.

The size of an array is known at compile- The size of a structure may not be known
time. until runtime.

Arrays can only store elements of the Structures can store elements of different
same data type. data types.

Array elements have default values based Structure members do not have default
on their data type (e.g., 0 for integers). values and must be initialized explicitly.

Arrays are more suitable for storing Structures are more suitable for storing
homogeneous data (e.g., a list of heterogeneous data (e.g., details about a
numbers). person).
Unit 2

Q. Write short on any three:


1)Dynamic memory allocation.
2)Pointer to array and array of pointers.
3)Pointer within Structure.
4)Union
Dynamic Memory Allocation

1. Dynamic memory allocation refers to the process of allocating memory at runtime


rather than at compile time.
2. It allows programs to allocate memory as needed, which can be useful when the size
of the data is unknown or may change during program execution.
3. Dynamic memory allocation is typically done using functions such as malloc(),
calloc(), and realloc() in C/C++ or new operator in languages like C++.
4. When dynamically allocating memory, it is important to properly manage and
deallocate the memory to avoid memory leaks and other issues.
5. Dynamic memory allocation can be used to create data structures such as linked lists,
trees, and dynamic arrays.
6. It allows for more efficient use of memory by allocating only the required amount of
memory.
7. Dynamic memory allocation can also be used to allocate memory for objects with
varying lifetimes, such as temporary variables or objects created during program
execution.

Pointer to Array and Array of Pointers

1. A pointer to an array refers to a pointer that points to the first element of an array.
2. It can be used to access elements of the array using pointer arithmetic.
3. Pointer to an array can be declared using the syntax: datatype (*ptr)[size];
4. An array of pointers refers to an array where each element is a pointer.
5. It can be used to store addresses of other variables or objects.
6. Array of pointers is often used in situations where a collection of objects needs to be
dynamically allocated or managed.
7. Array of pointers can be declared using the syntax: datatype *array[size];

Pointer within Structure

1. A pointer within a structure refers to a member variable of a structure that is of


pointer type.
2. It allows a structure to hold the address or reference to another variable or object.
Unit 2
3. Pointers within structures are commonly used in linked data structures such as linked
lists, trees, and graphs.
4. They enable efficient traversal and manipulation of the data structure.
5. Pointers within structures can be used to create self-referential structures where a
structure contains a pointer to another structure of the same type.
6. Pointers within structures can also be used to implement dynamic polymorphism in
object-oriented programming.
7. Proper memory management is crucial when using pointers within structures to avoid
memory leaks or accessing invalid memory locations.

Union

1. A union is a data structure that allows different types of data to be stored in the same
memory location.
2. It enables efficient use of memory by sharing the same memory space for different
variables.
3. The size of a union is determined by the largest member variable.
4. Only one member variable of a union can be accessed at a time.
5. Unions are often used in situations where different types of data need to be stored or
accessed interchangeably.
6. Unions can be useful in low-level programming when dealing with hardware registers
or bit manipulation.
7. Care should be taken when using unions to ensure proper type casting and avoid
unintended behavior.

Q. Summarize dynamic memory allocation in C with


example.
Dynamic Memory Allocation in C

Dynamic memory allocation in C refers to the process of allocating memory at runtime. This
allows the programmer to allocate memory as and when needed during program execution.
The malloc(), calloc(), realloc(), and free() functions are commonly used for
dynamic memory allocation in C.

malloc() Function The malloc() function is used to allocate a specified number of bytes of
memory. It returns a pointer of type void which can be cast into a pointer of any form.

Example:

int *ptr;
ptr = (int*)malloc(5 * sizeof(int));

In this example, the malloc() function allocates memory for an array of 5 integers.

calloc() Function The calloc() function is used to allocate space for multiple elements, and
it initializes the allocated memory block with zero.

Example:
Unit 2
int *ptr;
ptr = (int*)calloc(5, sizeof(int));

In this example, the calloc() function allocates memory for an array of 5 integers and
initializes them to zero.

realloc() Function The realloc() function is used to resize the previously allocated
memory. It takes two arguments: a pointer to the previously allocated memory block and the
new size in bytes.

Example:

ptr = (int*)realloc(ptr, 10 * sizeof(int));

In this example, the realloc() function resizes the previously allocated memory block to
accommodate 10 integers.

free() Function The free() function is used to deallocate the dynamically allocated
memory. It releases the memory block pointed by the pointer, making it available for further
allocation.

Example:

free(ptr);

In this example, the free() function deallocates the memory block pointed by ptr.

Dynamic memory allocation in C is a powerful feature that allows for efficient use of
memory resources during program execution. However, it also requires careful management
to avoid memory leaks and other issues.

Q. Relate and demonstrate pointers with 2D arrays.


Pointers and 2D Arrays

In C and C++ programming languages, pointers and 2D arrays are closely related. A pointer
is a variable that stores the memory address of another variable, while a 2D array is an array
of arrays, representing a table of elements. Pointers can be used to access and manipulate 2D
arrays in various ways.

Pointer to 2D Array

In C and C++, a pointer to a 2D array can be declared using the following syntax:

int (*ptr)[cols];

Here, ptr is a pointer to a 2D array with cols columns. This allows for dynamic memory
allocation and manipulation of 2D arrays using pointers.

Accessing Elements Using Pointers


Unit 2
Pointers can be used to access elements of a 2D array. For example, given a 2D array arr, the
element at row i and column j can be accessed using pointer arithmetic as follows:

*(*(arr + i) + j)

This expression dereferences the pointer to the ith row and then accesses the jth element
within that row.

Passing 2D Arrays to Functions

When passing a 2D array to a function, it is common to use pointers. Since arrays decay into
pointers when passed to functions, a 2D array can be represented as a pointer to an array. For
example:

void func(int (*arr)[cols]) {


// Function body
}

This allows for efficient passing of large 2D arrays without incurring the overhead of copying
the entire array.

Dynamic Memory Allocation

Pointers are often used for dynamic memory allocation of 2D arrays. By using pointers, it is
possible to allocate memory for a 2D array at runtime using functions such as malloc or
calloc. This provides flexibility in managing memory for 2D arrays based on program
requirements.

Manipulating 2D Arrays Using Pointers

Pointers can be used to efficiently manipulate 2D arrays. For example, by iterating through
the rows and columns using pointers, various operations such as transposing a matrix or
performing matrix multiplication can be implemented with improved performance.

In summary, pointers and 2D arrays are closely related in C and C++ programming
languages. Pointers provide flexibility in accessing, passing, dynamically allocating memory
for, and manipulating 2D arrays efficiently.

Q. Print names and numbers of employees who have 5


year or more experience and salary
less than Rs. 10,000 using array of structures (name,
number, experience and salary).
According to www.iAsk.ai Ask Ai Search Engine:
Unit 2
C Code to Print Names and Numbers of Employees

To achieve this task, we can use an array of structures in C to store the employee details such
as name, number, experience, and salary. We can then iterate through the array to find
employees with 5 years or more experience and a salary less than Rs. 10,000.

#include

struct Employee {
char name[50];
int number;
int experience;
float salary;
};

int main() {
struct Employee employees[5] = {
{"John", 1, 7, 9000},
{"Alice", 2, 3, 12000},
{"Bob", 3, 5, 8000},
{"Eve", 4, 6, 11000},
{"Mike", 5, 8, 9500}
};

printf("Employees with 5 or more years of experience and salary less


than Rs. 10,000:\n");
for (int i = 0; i < 5; i++) {
if (employees[i].experience >= 5 && employees[i].salary < 10000) {
printf("Name: %s, Number: %d\n", employees[i].name,
employees[i].number);
}
}

return 0;
}

In this code snippet, we define a structure Employee with fields for name, number,
experience, and salary. We then create an array of Employee structures and initialize it with
some sample data. The main function iterates through the array and prints the names and
numbers of employees who meet the specified criteria.

Q. Write a function to swap values of two numbers


using pointers.
Function to Swap Values of Two Numbers Using Pointers in C

In C, you can swap the values of two numbers using pointers. Pointers are variables that store
the memory address of another variable. By using pointers, you can directly manipulate the
values at those memory addresses, allowing you to swap the values of two variables without
needing a temporary variable.

Here’s a function to swap the values of two numbers using pointers in C:


Unit 2
void swap(int *ptr1, int *ptr2) {
int temp = *ptr1;
*ptr1 = *ptr2;
*ptr2 = temp;
}

In this function, int *ptr1 and int *ptr2 are pointers to integers. Inside the function, we
use a temporary variable temp to hold the value pointed to by ptr1, then assign the value
pointed to by ptr2 to ptr1, and finally assign the value in temp to ptr2. This effectively
swaps the values of the two numbers.

To use this function, you can pass the addresses of the variables you want to swap as
arguments:

int a = 10;
int b = 20;

swap(&a, &b);

After calling this function, the values of a and b will be swapped.

Or

Sure, here is a function to swap the values of two numbers using pointers in C:
C
void swap(int *a, int *b) {
int temp = *a;
*a = *b;
*b = temp;
}
To use this function, you would call it with the addresses of the two numbers you
want to swap. For example, the following code will swap the values of the variables a
and b:
C
int a = 10;
int b = 20;

swap(&a, &b);

printf("a = %d, b = %d\n", a, b); // Output: a = 20, b = 10


Here is a breakdown of the function code:
• void swap(int *a, int *b): This line declares the function named swap,
which takes two integer pointers as arguments.
• int temp = *a;: This line creates a temporary variable temp and assigns it
the value of the variable pointed to by a.
Unit 2
• *a = *b;: This line assigns the value of the variable pointed to by b to the
variable pointed to by a.
• *b = temp;: This line assigns the value of temp to the variable pointed to by
b.

You might also like