SlideShare a Scribd company logo
Unit 3(Arrays)
By
M. Srinuvasu Rao Naidu
Asst. prof(SSCE)
C arrays(Introduction)
•An array is defined as the collection of similar type of data items
stored at contiguous memory locations.
•Arrays are the derived data type in C programming language which
can store the primitive type of data such as int, char, double, float, etc.
It also has the capability to store the collection of derived data types,
such as pointers, structure, etc.
•The array is the simplest data structure where each data element can be
randomly accessed by using its index number.
•C array is beneficial if you have to store similar elements. For
example, if we want to store the marks of a student in 6 subjects, then
we don't need to define different variables for the marks in the different
subject.
•Instead of that, we can define an array which can store the marks in
each subject at the contiguous memory locations.
•By using the array, we can access the elements easily. Only a few lines
of code are required to access the elements of the array.
C arrays(Introduction)
* Each element of an array is of same data type and carries the same size, i.e.,
int = 4 bytes.
* Elements of the array are stored at contiguous memory locations where the
first element is stored at the smallest memory location.
* Elements of the array can be randomly accessed since we can calculate the
address of each element of the array with the given base address and the size of
the data element.
Advantage of C Array
1) Code Optimization: Less code to the access the data.
2) Ease of traversing: By using the for loop, we can retrieve the elements of an
array easily.
3) Ease of sorting: To sort the elements of the array, we need a few lines of
code only.
4) Random Access: We can access any element randomly using the array.
Disadvantage of C Array
1) Fixed Size: Whatever size, we define at the time of declaration of the array,
we can't exceed the limit. So, it doesn't grow the size dynamically like
LinkedList which we will learn later.
Unit 3(Arrays).pptx arrays topics in the c lang
Unit 3(Arrays).pptx arrays topics in the c lang
Unit 3(Arrays).pptx arrays topics in the c lang
Arrays Initialization
2. Array Initialization with Declaration without Size
Syntex:
data_type array_name[] = {1,2,3,4,5};
3. Array Initialization after Declaration (Using Loops)
Syntex
for (int i = 0; i < N; i++)
{
array_name[i] = valuei;
}
1. Array Initialization with Declaration
Arrays Initialization
// C Program to demonstrate array initialization
#include <stdio.h>
int main()
{
// array initialization using initialier list
int arr[5] = { 10, 20, 30, 40, 50 };
// array initialization using initializer list without
// specifying size
int arr1[] = { 1, 2, 3, 4, 5 };
// array initialization using for loop
float arr2[5];
for (int i = 0; i < 5; i++) {
arr2[i] = (float)i * 2.1;
}
return 0;
}
Unit 3(Arrays).pptx arrays topics in the c lang
Unit 3(Arrays).pptx arrays topics in the c lang
Unit 3(Arrays).pptx arrays topics in the c lang
Access Array Elements
We can access any element of an array in C using the array subscript operator [ ] and
the index value i of the element.
array_name [index];
Access Array Elements
// C Program to illustrate element access using array
#include <stdio.h>
int main()
{
// array declaration and initialization
int arr[5] = { 15, 25, 35, 45, 55 };
// accessing element at index 2 i.e 3rd element
printf("Element at arr[2]: %dn", arr[2]);
// accessing element at index 4 i.e last element
printf("Element at arr[4]: %dn", arr[4]);
// accessing element at index 0 i.e first element
printf("Element at arr[0]: %d", arr[0]);
return 0;
}
Out Put:
Element at arr[2]: 35
Element at arr[4]: 55
Element at arr[0]: 15
Arrays(operations)
Update Array Element
We can update the value of an element at the given index i in a similar
way to accessing an element by using the array subscript operator [ ] and
assignment operator =.
array_name[i] = new_value;
C Array Traversal
Traversal is the process in which we visit every element of the
data structure. For C array traversal, we use loops to iterate through each
element of the array.
Array Traversal using for Loop
for (int i = 0; i < N; i++)
{
array_name[i];
}
// C Program to demonstrate the use of array
#include <stdio.h>
int main()
{
// array declaration and initialization
int arr[5] = { 10, 20, 30, 40, 50 };
// modifying element at index 2
arr[2] = 100;
// traversing array using for loop
printf("Elements in Array: ");
for (int i = 0; i < 5; i++) {
printf("%d ", arr[i]);
}
return 0;
}
Out Put:
Elements in Arraya: 10 20 100 40 50
Unit 3(Arrays).pptx arrays topics in the c lang
Unit 3(Arrays).pptx arrays topics in the c lang
Unit 3(Arrays).pptx arrays topics in the c lang
Unit 3(Arrays).pptx arrays topics in the c lang
Unit 3(Arrays).pptx arrays topics in the c lang
Unit 3(Arrays).pptx arrays topics in the c lang
Unit 3(Arrays).pptx arrays topics in the c lang
Unit 3(Arrays).pptx arrays topics in the c lang
Unit 3(Arrays).pptx arrays topics in the c lang
Unit 3(Arrays).pptx arrays topics in the c lang
Unit 3(Arrays).pptx arrays topics in the c lang
Unit 3(Arrays).pptx arrays topics in the c lang
Unit 3(Arrays).pptx arrays topics in the c lang
Unit 3(Arrays).pptx arrays topics in the c lang
Unit 3(Arrays).pptx arrays topics in the c lang
Unit 3(Arrays).pptx arrays topics in the c lang
Unit 3(Arrays).pptx arrays topics in the c lang
Unit 3(Arrays).pptx arrays topics in the c lang
Unit 3(Arrays).pptx arrays topics in the c lang
Unit 3(Arrays).pptx arrays topics in the c lang
Unit 3(Arrays).pptx arrays topics in the c lang
Unit 3(Arrays).pptx arrays topics in the c lang
Unit 3(Arrays).pptx arrays topics in the c lang
C Pointers
Pointers are one of the core components of the C programming language. A
pointer can be used to store the memory address of other variables, functions, or even
other pointers. The use of pointers allows low-level memory access, dynamic memory
allocation, and many other functionality in C.
What is a Pointer in C?
A pointer is defined as a derived data type that can store the address of other C variables
or a memory location. We can access and manipulate the data stored in that memory
location using pointers.
As the pointers in C store the memory addresses, their size is independent of the type of
data they are pointing to. This size of pointers in C only depends on the system
architecture.
Syntax of C Pointers
The syntax of pointers is similar to the variable declaration in C, but we use the ( * )
dereferencing operator in the pointer declaration.
datatype * ptr;
where
•ptr is the name of the pointer.
•datatype is the type of data it is pointing to.
The above syntax is used to define a pointer to a variable. We can also define pointers to
functions, structures, etc.
C Pointers
How to Use Pointers?
The use of pointers in C can be divided into three steps:
1. Pointer Declaration
2. Pointer Initialization
3. Pointer Dereferencing
1. Pointer Declaration
In pointer declaration, we only declare the pointer but do not initialize it. To
declare a pointer, we use the ( * ) dereference operator before its name.
Example
int *ptr;
The pointer declared here will point to some random memory address as it is
not initialized. Such pointers are called wild pointers.
C Pointers
2. Pointer Initialization
Pointer initialization is the process where we assign some initial value to the pointer
variable. We generally use the ( &: ampersand ) addressof operator to get the memory
address of a variable and then store it in the pointer variable.
Example
int var = 10;
int * ptr;
ptr = &var;We can also declare and initialize the pointer in a single step. This method is
called pointer definition as the pointer is declared and initialized at the same time.
Example
int *ptr = &var;Note: It is recommended that the pointers should always be initialized to
some value before starting using it. Otherwise, it may lead to number of errors.
C Pointers
3. Pointer Dereferencing
Dereferencing a pointer is the process of accessing the value stored in the memory
address specified in the pointer. We use the same ( * ) dereferencing operator that we
used in the pointer declaration.
Dereferencing a Pointer in C
C Pointers
C Pointer Example
// C program to illustrate Pointers
#include <stdio.h>
void geeks()
{
int var = 10;
int* ptr; // declare pointer variable
// note that 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()
{
geeks();
return 0;
}
Output :Value at ptr = 0x7ffca84068dc Value at var = 10 Value at *ptr = 1
C Pointers
Size of Pointers in C
The size of the pointers in C is equal for every pointer type. The size of the pointer
does not depend on the type it is pointing to. It only depends on the operating system
and CPU architecture. The size of pointers in C is
1. 8 bytes for a 64-bit System
2. 4 bytes for a 32-bit System
•The reason for the same size is that the pointers store the memory addresses, no
matter what type they are.
•As the space required to store the addresses of the different memory locations is the
same, the memory required by one pointer type will be equal to the memory required
by other pointer types.
Example:
printf("Size of Integer Pointer t:t%d bytesn", sizeof(ptr_int));
printf("Size of Character Pointert:t%d bytesn", sizeof(ptr_char));
printf("Size of Structure Pointert:t%d bytesn", sizeof(ptr_str));
printf("Size of Function Pointert:t%d bytesn", sizeof(ptr_func));
printf("Size of NULL Void Pointert:t%d bytes", sizeof(ptr_vn));
C Pointers
Types of Pointers in C
Pointers in C can be classified into many different types based on the parameter on
which we are defining their types. If we consider the type of variable stored in the
memory location pointed by the pointer, then the pointers can be classified into the
following types:
1. Integer Pointers
As the name suggests, these are the pointers that point to the integer values.
Syntax
int *ptr;
These pointers are pronounced as Pointer to Integer.
Similarly, a pointer can point to any primitive data type. It can point also point to
derived data types such as arrays and user-defined data types such as structures.
2. Array Pointer
Pointers and Array are closely related to each other. Even the array name is the pointer
to its first element. They are also known as Pointer to Arrays. We can create a pointer to
an array using the given syntax.
Syntax
char *ptr = &array_name;
Pointer to Arrays exhibits some interesting properties which we discussed later in this
article.
C Pointers
3. Structure Pointer
The pointer pointing to the structure type is called Structure Pointer or Pointer to
Structure. It can be declared in the same way as we declare the other primitive data
types.
Syntax
struct struct_name *ptr;
In C, structure pointers are used in data structures such as linked lists, trees, etc.
4. Function Pointers
Function pointers point to the functions. They are different from the rest of the pointers
in the sense that instead of pointing to the data, they point to the code. Let’s consider a
function prototype – int func (int, char), the function pointer for this function will be
Syntax
int (*ptr)(int, char);
Note: The syntax of the function pointers changes according to the function prototype.
C Pointers
5. Double Pointers
In C language, we can define a pointer that stores the memory address of another
pointer. Such pointers are called double-pointers or pointers-to-pointer. Instead of
pointing to a data value, they point to another pointer.
Syntax
datatype ** pointer_name;
Dereferencing Double Pointer
*pointer_name; // get the address stored in the inner level pointer
**pointer_name; // get the value pointed by inner level pointer
Note:
In C, we can create multi-level pointers with any number of levels such as – ***ptr3,
****ptr4, ******ptr5 and so on.
C Pointers
6. NULL Pointer
The Null Pointers are those pointers that do not point to any memory location. They can
be created by assigning a NULL value to the pointer. A pointer of any type can be
assigned the NULL value.
Syntax
data_type *pointer_name = NULL;
or
pointer_name = NULL
It is said to be good practice to assign NULL to the pointers currently not in use.
7. Void Pointer
The Void pointers in C are the pointers of type void. It means that they do not have any
associated data type. They are also called generic pointers as they can point to any type
and can be typecasted to any type.
Syntax
void * pointer_name;
One of the main properties of void pointers is that they cannot be dereferenced.
C Pointers
8. Wild Pointers
The Wild Pointers are pointers that have not been initialized with something yet. These
types of C-pointers can cause problems in our programs and can eventually cause them
to crash. If values is updated using wild pointers, they could cause data abort or data
corruption.
Example
int *ptr;
char *str;
9. Constant Pointers
In constant pointers, the memory address stored inside the pointer is constant and cannot
be modified once it is defined. It will always point to the same memory address.
Syntax
data_type * const pointer_name;
10. Pointer to Constant
The pointers pointing to a constant value that cannot be modified are called pointers to a
constant. Here we can only access the data pointed by the pointer, but cannot modify it.
Although, we can change the address stored in the pointer to constant.
Syntax
const data_type * pointer_name;
C Pointers
Other Types of Pointers in C:
There are also the following types of pointers available to use in C apart from those
specified above:
Far pointer: A far pointer is typically 32-bit that can access memory outside the current
segment.
Dangling pointer: A pointer pointing to a memory location that has been deleted (or
freed) is called a dangling pointer.
Huge pointer: A huge pointer is 32-bit long containing segment address and offset
address.
Complex pointer: Pointers with multiple levels of indirection.
Near pointer: Near pointer is used to store 16-bit addresses means within the current
segment on a 16-bit machine.
Normalized pointer: It is a 32-bit pointer, which has as much of its value in the
segment register as possible.
File Pointer: The pointer to a FILE data type is called a stream pointer or a file pointer.
C Pointers
pointer expressions and address arithmetic:
1. Pointer Expression:
A pointer is a variable that stores the memory address of another variable.
Pointer expressions allow us to perform operations on these pointers. For
example, consider the following expression:
int *ptr = &var; // ptr stores the address of var
Here, ptr is a pointer to an integer variable var.
Common pointer operations include dereferencing (using *ptr to access the
value at the address) and assigning addresses.
C Pointers
2. Address Arithmetic:
Pointers can be used in arithmetic operations to navigate through memory. C supports
pointer arithmetic, allowing you to move a pointer across memory locations:
Increment (ptr + 1): Moves the pointer to the next memory location (depends on the
data type size). For example, if ptr points to an integer, ptr + 1 moves the pointer to the
next integer (which is typically 4 bytes away).
Decrement (ptr - 1): Moves the pointer to the previous memory location.
Difference (ptr2 - ptr1): Calculates how many elements are between two pointers.
Example of Address Arithmetic:
int arr[5] = {10, 20, 30, 40, 50};
int *ptr = arr; // ptr points to the first element of the array
printf("%dn", *(ptr + 2)); // Output: 30,
accessing the third element via pointer arithmetic
* In this case, ptr + 2 points to the third element in the array arr. Address arithmetic is
useful when working with arrays, structures, and dynamic memory.
C Pointers
Example : Basic Pointer Expression
#include <stdio.h>
int main()
{
int var = 100;
int *ptr; // Declare an integer pointer
ptr = &var; // Store the address of var in ptr
printf("Value of var: %dn", var); // Output: 100
printf("Address of var: %pn", &var); // Output: Address of var
printf("Pointer ptr holds address: %pn", ptr); // Output: Same as &var
printf("Value at the address ptr is pointing to: %dn", *ptr); // Output: 100 return 0;
}
C Pointers
Example 2: Pointer Arithmetic with Arrays
#include <stdio.h>
int main()
{
int arr[5] = {10, 20, 30, 40, 50};
int *ptr = arr; // Points to the first element of the array
// Pointer arithmetic to access array elements
printf("First element: %dn", *ptr); // Output: 10
printf("Second element: %dn", *(ptr + 1)); // Output: 20
printf("Third element: %dn", *(ptr + 2)); // Output: 30
// Incrementing pointer to move to next element
ptr++; // Now ptr points to the second element
printf("Value after ptr++: %dn", *ptr); // Output: 20
return 0;
}
•ptr + 1 moves the pointer to the next element in the a
• we can assign arr[1] = ptr [1 ]
C Pointers
C Pointer Example
// C program to illustrate Pointers
#include <stdio.h>
void geeks()
{
int var = 10;
int* ptr; // declare pointer variable
// note that 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()
{
geeks();
return 0;
}
Output :Value at ptr = 0x7ffca84068dc Value at var = 10 Value at *ptr = 1
Array and Pointers
The relationship between arrays and pointers in C is close, but they are not the same
thing. Here's a brief explanation:
1. Arrays as Pointers
The name of an array (e.g., arr) acts like a pointer to its first element.
For example, if you declare int arr[3] = {10, 20, 30};, then arr is equivalent to &arr[0]
* You can use a pointer to access array elements:c
int *ptr = arr; // ptr points to arr[0]
printf("%dn", *ptr); // Outputs 10
2.Pointer Arithmetic with Arrays
You can use pointer arithmetic to traverse an array.c
printf("%dn", *(arr + 1)); // Outputs 20 (equivalent to arr[1])
3. Differences Between Arrays and Pointers
Fixed Size: Arrays have a fixed size and cannot be reassigned.c
int arr[5]; // Size is fixed
Reassignable: Pointers are variables that can point to different memory addresses.c
int num = 5; int *p = &num; p = arr; // Pointer can be reassigned
Arrays are contiguous blocks of memory . Arrays can't be resized or reassigned, but
pointers can. sizeof(arr) gives the total size of the array, while sizeof(ptr) gives the size
of the pointer (not the size of what it points to).
Array as a Function Argument
When you pass an array as a function argument in C, what actually gets passed is
a pointer to the first element of the array, not the entire array itself.
Key Points:
Array Decays to Pointer:
When an array is passed to a function, it "decays" into a pointer to its first
element.
For example, if you pass arr to a function, it is treated as &arr[0].
Function Declaration:
You can declare the function parameter as either an array or a pointer; both
mean the same thing:c
Copy code
void printArray(int arr[], int size); // Treated as a pointer void printArray(int
*arr, int size); // Equivalent declaration
Why Only the Pointer Gets Passed:
Passing the entire array would be inefficient because arrays can be large.
Instead, only the address of the first element is passed, which is much faster.
No Size Information:
Since only the pointer is passed, the function doesn't know the size of the
array.
You need to pass the size as a separate argument.
Cont…
Example for Array As a function Argument
#include <stdio.h>
void printArray(int arr[], int size) {
for (int i = 0; i < size; i++) {
printf("%d ", arr[i]);
}
printf("n");
}
int main() {
int numbers[] = {10, 20, 30, 40, 50};
printArray(numbers, 5); // Passing array to function
return 0;
}
Output: 10 20 30 40 50
Generic pointer
In C, a generic pointer is a special type of pointer that can point to any data type. The
type used for generic pointers is void *. Let's break down what a generic pointer is, why
it's useful, and how to use it.
1. What is a Generic Pointer (void *)?
A generic pointer is declared using the void * type.
Unlike other pointers (e.g., int *, char *), a void * pointer does not have an associated
data type.
It can hold the address of any data type (e.g., int, float, char, structs).
2. Why Use Generic Pointers?
Flexibility: They allow you to write functions that can work with any data type.
Memory Management: Commonly used in functions like malloc(), calloc(), and free()
for dynamic memory allocation, which return or accept a void * pointer.
Data Structures: Useful in implementing data structures like linked lists, stacks, or
queues that can store any type of data.
3. How to Use Generic Pointers
You can assign the address of any type of variable to a void * pointer.
However, to access or manipulate the data, you need to cast the void * pointer to the
appropriate type.
Generic Pointer
Example:
#include <stdio.h>
int main() {
int num = 42;
float pi = 3.14;
void *ptr; // Declare a generic pointer
ptr = &num; // Point to an integer
printf("Integer value: %dn", *(int *)ptr); // Cast to int *
ptr = &pi; // Point to a float
printf("Float value: %.2fn", *(float *)ptr); // Cast to float *
return 0;
}
Output: Integer value: 42
Float value: 3.14
* Cannot Dereference Directly: You cannot directly dereference a void * pointer since
it doesn't know what type of data it points to. You must cast it to the correct type first.
* Type Safety: Using void * pointers can be powerful but also dangerous because the
compiler won't check if you're using the correct type. It's up to you to ensure the cast is
correct.
Null pointer
In C, a null pointer is a special type of pointer that doesn't point to any valid memory
location. It is used to indicate that the pointer is not currently pointing to any object or
function. Let's explore what null pointers are, how they are used, and why they are
important.
1. What is a Null Pointer?
A null pointer is a pointer that has been assigned a value of NULL.
NULL is a macro defined in <stddef.h>, <stdio.h>, <stdlib.h>, or <string.h> as ((void
*)0).
This means a null pointer points to address 0, which is reserved by the system and
cannot be accessed by the user program.
2. Why Use Null Pointers?
Indicating Unused Pointers: A null pointer is used to indicate that the pointer does not
currently reference a valid memory location. This helps in avoiding accidental
dereferencing of uninitialized pointers.
Error Handling: Functions that return pointers can use NULL to indicate failure (e.g.,
malloc() returns NULL if it fails to allocate memory).
Linked Data Structures: In data structures like linked lists or trees, null pointers are
used to indicate the end of the list or absence of child nodes.
Null Pointer
Example:
#include <stdio.h>
int main() {
int *ptr = NULL; // Initialize a null pointer
if (ptr == NULL) {
printf("Pointer is null.n");
} else {
printf("Pointer is not null.n");
}
return 0;
}
Output:
Pointer is null.
Important Points about Null Pointers
A null pointer does not point to any valid object or function.
It is good practice to initialize pointers to NULL if you don't have a valid address for them
initially.
Comparing pointers to NULL is a common way to check if they are pointing to valid
memory.
The constant NULL is typically defined as (void *)0, but you can just use NULL without
worrying about the exact definition.
Pointer to Pointer
In C, a pointer to a pointer (or double pointer) is a type of pointer that stores the address of
another pointer. This means it's a pointer that points to another pointer, which in turn points to
a data value.
1. What is a Pointer to a Pointer?
A pointer to a pointer is declared using two asterisks (**).
It can be used to store the address of a pointer variable.
Declaration Example:
int x = 10; // An integer variable
int *ptr = &x; // A pointer to an integer
int **ptr2 = &ptr; // A pointer to a pointer
2. Visual Representation
Assuming x is stored at address 0x100, ptr is stored at address 0x200, and ptr2 is stored at
address 0x300, the memory layout would look like this:
3. Accessing Values Using a Pointer to a Pointer
*ptr2 gives you the value stored in ptr (which is the address of x).
**ptr2 gives you the value of x. Use Cases for Pointer to Pointer
Dynamic Memory Allocation (2D Arrays): They are often used for creating multi-dimensional
Pointer to Pointer
Use Cases for Pointer to Pointer
Dynamic Memory Allocation (2D Arrays): They are often used for creating multi-dimensional
arrays dynamically.
Function Parameters: They allow functions to modify the original pointers passed to them (e.g., to
allocate memory inside a function).
Linked Data Structures: Used in linked lists, trees, and other data structures where you need to
modify the next pointers
Example:
#include <stdio.h>
int main() {
int x = 42;
int *ptr = &x;
int **ptr2 = &ptr;
printf("Value of x: %dn", x);
printf("Value of x using *ptr: %dn", *ptr);
printf("Value of x using **ptr2: %dn", **ptr2);
printf("Address of x: %pn", (void *)&x);
printf("Address stored in ptr: %pn", (void *)ptr);
printf("Address stored in ptr2: %pn", (void *)ptr2);
return 0;
}
Output:
Value of x: 42
Value of x using *ptr: 42
Value of x using **ptr2: 42
Address of x: 0x7ffee4b7482c (example)
Address stored in ptr: 0x7ffee4b7482c (example)
Address stored in ptr2: 0x7ffee4b74820
Dynamic Memory allocation
Dynamic memory allocation in C is a way to allocate memory at runtime (i.e., while
your program is running) rather than at compile time. This is particularly useful when
you don't know the exact amount of memory your program will need before it starts
executing. It allows for more flexible and efficient use of memory, especially in
situations where data sizes may vary or are determined by user input.
Key Concepts of Dynamic Memory Allocation
In C, dynamic memory allocation is achieved using several standard library functions
defined in <stdlib.h>:
1. malloc() (Memory Allocation)
2. calloc() (Contiguous Allocation)
3. realloc() (Reallocation)
4. free() (Deallocation)
Malloc ( )
1. malloc(): Memory Allocation
Purpose: Allocates a block of memory of the specified size (in bytes).
Syntax:
void *malloc (size_t size);
Returns: A pointer to the beginning of the block of memory allocated, or NULL if
the allocation fails.
Example:
int *ptr = (int *)malloc(4 * sizeof(int)); // Allocates memory for 4 integers
if (ptr == NULL) {
printf("Memory allocation failed.n");
exit(1);
}
Calloc ( )
2. calloc(): Contiguous Allocation
Purpose: Similar to malloc(), but also initializes the allocated memory to zero.
Syntax:
void *calloc(size_t num, size_t size);
Returns: A pointer to the allocated memory, or NULL if the allocation fails.
Example:
int *ptr = (int *)calloc(4, sizeof(int)); // Allocates memory for 4 integers, initializes to 0
if (ptr == NULL) {
printf("Memory allocation failed.n");
exit(1);
}
Realloc ( )
3. realloc(): Reallocation
Purpose: Changes the size of previously allocated memory block (using malloc() or
calloc()).
Syntax:
void *realloc(void *ptr, size_t newSize);
Returns: A pointer to the newly allocated memory, or NULL if the reallocation fails.
If NULL is returned, the original memory block is not freed.
Example:
ptr = (int *)realloc(ptr, 8* sizeof(int)); // Resizes the memory to fit 8 integers
if (ptr == NULL) {
printf("Memory reallocation failed.n");
exit(1);
}
Free ( )
free(): Deallocation
Purpose: Frees memory that was previously allocated with malloc(), calloc(), or
realloc().
Syntax:
void free(void *ptr);
Example:
free(ptr); // Frees the allocated memory
ptr = NULL; // Good practice to set pointer to NULL after freeing
Example
#include <stdio.h>
#include <stdlib.h>
int main() {
int n;
printf("Enter number of elements: ");
scanf("%d", &n);
int *arr = (int *)malloc(n * sizeof(int)); // Dynamically allocate memory for n integers
if (arr == NULL) {
printf("Memory allocation failed.n");
return 1;
}
printf("Enter %d elements:n", n); // Input elements
for (int i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}
printf("You entered: "); // Print elements
for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
printf("n");
free(arr); // Free allocated memory
return 0;
}
Out Put:
Enter number of elements: 3
Enter 3 elements:
5 10 15
You entered: 5 10 15
Pointer as a function arguments
In C, you can pass pointers as function arguments to allow the function to access and
modify variables outside its own scope. This is particularly useful for:
Passing large data structures efficiently (like arrays or structures) without copying
them.
Modifying the values of variables in the calling function.
Working with dynamically allocated memory.
Let's explore how pointers can be used as function arguments in various ways.
Basic Example: Passing a Pointer to a Function
Example 1: Using Pointers to Modify Variable Values
#include <stdio.h>
void updateValue(int *ptr) { // Function that takes a pointer as an argument
*ptr = 20; // Dereference the pointer and change the value it points to
}
int main() {
int num = 10;
printf("Before: num = %dn", num);
updateValue(&num); // Pass the address of num to the function
printf("After: num = %dn", num);
return 0;
}
Out Put: Before: num = 10 After: num = 20
Example
Example: Passing Arrays to Functions
#include <stdio.h>
void printArray(int *arr, int size) { // Function to print an array
for (int i = 0; i < size; i++) {
printf("%d ", arr[i]);
}
printf("n");
}
int main() {
int numbers[] = {1, 2, 3, 4, 5};
int size = sizeof(numbers) / sizeof(numbers[0]);
// Passing the array to the function
printArray(numbers, size);
return 0;
}
Out Put:
1 2 3 4 5
Dangling Pointer
A dangling pointer in C is a pointer that references a memory location that has been
freed or deallocated. In other words, it's a pointer that points to memory that is no
longer valid. Dangling pointers can lead to undefined behavior, including program
crashes, data corruption, or security vulnerabilities.
1. A dangling pointer points to memory that has been freed or is no longer valid.
2. They commonly occur after deallocating memory, returning pointers to local
variables, or reassigning pointers.
3. Dangling pointers can cause crashes, data corruption, and security issues.
4. To avoid dangling pointers, always set pointers to NULL after freeing them, avoid
returning pointers to local variables, and use tools to detect memory issues.
Dangling Pointer
#include <stdio.h>
#include <stdlib.h>
int main() {
int *ptr = (int *)malloc(sizeof(int));
// Step 1: Dynamically allocate memory for an integer
if (ptr == NULL) {
printf("Memory allocation failed.n");
return 1;
}
*ptr = 42;
// Step 2: Assign a value to the allocated memory
printf("Value before free: %dn", *ptr); // Outputs: 42
// Step 3: Free the allocated memory
free(ptr);
// Step 4: ptr is now a dangling pointer (points to freed memory)
printf("Value after free (dangling): %dn", *ptr); // Undefined behavior!
// Step 5: Avoid dangling pointer by setting it to NULL
ptr = NULL;
return 0;
}
Command line Arguments in c
In C, command line arguments allow you to pass information to your program when
you run it from the terminal (or command prompt). These arguments are provided to the
main() function as parameters.
Syntax of main() with Command Line Arguments
int main(int argc, char *argv[])
* argc (Argument Count): An integer that represents the number of command line
arguments passed, including the program's name itself.
* argv (Argument Vector): An array of character pointers (strings) that holds all the
arguments passed to the program.
Key Points
argv[0] is the name of the program itself.
argv[1] to argv[argc-1] are the actual arguments passed by the user.
argc is always at least 1 because it includes the program name.
Simple Example: Printing Command Line
Arguments
#include <stdio.h>
int main(int argc, char *argv[]) {
printf("Number of arguments: %dn", argc);
// Loop through each argument and print it
for (int i = 0; i < argc; i++) {
printf("Argument %d: %sn", i, argv[i]);
}
return 0;
}
How to Run This Program
1. Save the code in a file, e.g., args.c.
2. Compile the code: bash
gcc args.c -o args
3. Run the program with command line arguments: bash
./args Hello World 123
Sample Output
Number of arguments: 4 Argument 0: ./args Argument 1: Hello Argument 2: World
Argument 3: 123

More Related Content

PDF
KSSR SEMAKAN RPT PK SJKC TAHUN 2
PDF
258509078 part-08-machies
PPTX
Computer science ( Structures In C ) Ppt
PPTX
Pointers in c - Mohammad Salman
PDF
Unit ii data structure-converted
PPT
ch08.ppt
PDF
pointer in c through addressing modes esntial in c
PPTX
Programming fundamentals week 12.pptx
KSSR SEMAKAN RPT PK SJKC TAHUN 2
258509078 part-08-machies
Computer science ( Structures In C ) Ppt
Pointers in c - Mohammad Salman
Unit ii data structure-converted
ch08.ppt
pointer in c through addressing modes esntial in c
Programming fundamentals week 12.pptx

Similar to Unit 3(Arrays).pptx arrays topics in the c lang (20)

PDF
Embedded C The IoT Academy
PPTX
arrays and pointers
PPTX
Pointers.pptx
PDF
Computer science abot c topics array 2d array
PPTX
Arrays in c language
PPTX
Arrays in c v1 09102017
PDF
Arraysincv109102017 180831194256
PPTX
C data types, arrays and structs
PPTX
3.ArraysandPointers.pptx
PPTX
UNIT 4 POINTERS.pptx pointers pptx for basic c language
PPT
c-arrays-pointers.ppt
PPT
c-arrays-pointer basics xxxx yyyy zzzzzzz
PPTX
unit-7 Pointerdesfsdfsdgsdgaa notes.pptx
PPTX
C Programming Unit-4
PDF
Module 02 Pointers in C
PDF
See through C
PPTX
Pointers in C Language
PDF
4.ArraysInC.pdf
PDF
Functions, Strings ,Storage classes in C
PPTX
c unit programming arrays in detail 3.pptx
Embedded C The IoT Academy
arrays and pointers
Pointers.pptx
Computer science abot c topics array 2d array
Arrays in c language
Arrays in c v1 09102017
Arraysincv109102017 180831194256
C data types, arrays and structs
3.ArraysandPointers.pptx
UNIT 4 POINTERS.pptx pointers pptx for basic c language
c-arrays-pointers.ppt
c-arrays-pointer basics xxxx yyyy zzzzzzz
unit-7 Pointerdesfsdfsdgsdgaa notes.pptx
C Programming Unit-4
Module 02 Pointers in C
See through C
Pointers in C Language
4.ArraysInC.pdf
Functions, Strings ,Storage classes in C
c unit programming arrays in detail 3.pptx
Ad

Recently uploaded (20)

PPTX
OOP with Java - Java Introduction (Basics)
PPTX
Current and future trends in Computer Vision.pptx
PPTX
CYBER-CRIMES AND SECURITY A guide to understanding
PPTX
CH1 Production IntroductoryConcepts.pptx
PPT
Mechanical Engineering MATERIALS Selection
PPTX
Lecture Notes Electrical Wiring System Components
DOCX
573137875-Attendance-Management-System-original
PPTX
MET 305 2019 SCHEME MODULE 2 COMPLETE.pptx
PPTX
CARTOGRAPHY AND GEOINFORMATION VISUALIZATION chapter1 NPTE (2).pptx
PDF
Mohammad Mahdi Farshadian CV - Prospective PhD Student 2026
PDF
Automation-in-Manufacturing-Chapter-Introduction.pdf
PDF
The CXO Playbook 2025 – Future-Ready Strategies for C-Suite Leaders Cerebrai...
PPTX
UNIT 4 Total Quality Management .pptx
PDF
R24 SURVEYING LAB MANUAL for civil enggi
PDF
composite construction of structures.pdf
PDF
BMEC211 - INTRODUCTION TO MECHATRONICS-1.pdf
PDF
Enhancing Cyber Defense Against Zero-Day Attacks using Ensemble Neural Networks
PDF
keyrequirementskkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkk
PPTX
Internet of Things (IOT) - A guide to understanding
PPTX
Safety Seminar civil to be ensured for safe working.
OOP with Java - Java Introduction (Basics)
Current and future trends in Computer Vision.pptx
CYBER-CRIMES AND SECURITY A guide to understanding
CH1 Production IntroductoryConcepts.pptx
Mechanical Engineering MATERIALS Selection
Lecture Notes Electrical Wiring System Components
573137875-Attendance-Management-System-original
MET 305 2019 SCHEME MODULE 2 COMPLETE.pptx
CARTOGRAPHY AND GEOINFORMATION VISUALIZATION chapter1 NPTE (2).pptx
Mohammad Mahdi Farshadian CV - Prospective PhD Student 2026
Automation-in-Manufacturing-Chapter-Introduction.pdf
The CXO Playbook 2025 – Future-Ready Strategies for C-Suite Leaders Cerebrai...
UNIT 4 Total Quality Management .pptx
R24 SURVEYING LAB MANUAL for civil enggi
composite construction of structures.pdf
BMEC211 - INTRODUCTION TO MECHATRONICS-1.pdf
Enhancing Cyber Defense Against Zero-Day Attacks using Ensemble Neural Networks
keyrequirementskkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkk
Internet of Things (IOT) - A guide to understanding
Safety Seminar civil to be ensured for safe working.
Ad

Unit 3(Arrays).pptx arrays topics in the c lang

  • 1. Unit 3(Arrays) By M. Srinuvasu Rao Naidu Asst. prof(SSCE)
  • 2. C arrays(Introduction) •An array is defined as the collection of similar type of data items stored at contiguous memory locations. •Arrays are the derived data type in C programming language which can store the primitive type of data such as int, char, double, float, etc. It also has the capability to store the collection of derived data types, such as pointers, structure, etc. •The array is the simplest data structure where each data element can be randomly accessed by using its index number. •C array is beneficial if you have to store similar elements. For example, if we want to store the marks of a student in 6 subjects, then we don't need to define different variables for the marks in the different subject. •Instead of that, we can define an array which can store the marks in each subject at the contiguous memory locations. •By using the array, we can access the elements easily. Only a few lines of code are required to access the elements of the array.
  • 3. C arrays(Introduction) * Each element of an array is of same data type and carries the same size, i.e., int = 4 bytes. * Elements of the array are stored at contiguous memory locations where the first element is stored at the smallest memory location. * Elements of the array can be randomly accessed since we can calculate the address of each element of the array with the given base address and the size of the data element. Advantage of C Array 1) Code Optimization: Less code to the access the data. 2) Ease of traversing: By using the for loop, we can retrieve the elements of an array easily. 3) Ease of sorting: To sort the elements of the array, we need a few lines of code only. 4) Random Access: We can access any element randomly using the array. Disadvantage of C Array 1) Fixed Size: Whatever size, we define at the time of declaration of the array, we can't exceed the limit. So, it doesn't grow the size dynamically like LinkedList which we will learn later.
  • 7. Arrays Initialization 2. Array Initialization with Declaration without Size Syntex: data_type array_name[] = {1,2,3,4,5}; 3. Array Initialization after Declaration (Using Loops) Syntex for (int i = 0; i < N; i++) { array_name[i] = valuei; } 1. Array Initialization with Declaration
  • 8. Arrays Initialization // C Program to demonstrate array initialization #include <stdio.h> int main() { // array initialization using initialier list int arr[5] = { 10, 20, 30, 40, 50 }; // array initialization using initializer list without // specifying size int arr1[] = { 1, 2, 3, 4, 5 }; // array initialization using for loop float arr2[5]; for (int i = 0; i < 5; i++) { arr2[i] = (float)i * 2.1; } return 0; }
  • 12. Access Array Elements We can access any element of an array in C using the array subscript operator [ ] and the index value i of the element. array_name [index];
  • 13. Access Array Elements // C Program to illustrate element access using array #include <stdio.h> int main() { // array declaration and initialization int arr[5] = { 15, 25, 35, 45, 55 }; // accessing element at index 2 i.e 3rd element printf("Element at arr[2]: %dn", arr[2]); // accessing element at index 4 i.e last element printf("Element at arr[4]: %dn", arr[4]); // accessing element at index 0 i.e first element printf("Element at arr[0]: %d", arr[0]); return 0; } Out Put: Element at arr[2]: 35 Element at arr[4]: 55 Element at arr[0]: 15
  • 14. Arrays(operations) Update Array Element We can update the value of an element at the given index i in a similar way to accessing an element by using the array subscript operator [ ] and assignment operator =. array_name[i] = new_value; C Array Traversal Traversal is the process in which we visit every element of the data structure. For C array traversal, we use loops to iterate through each element of the array. Array Traversal using for Loop for (int i = 0; i < N; i++) { array_name[i]; }
  • 15. // C Program to demonstrate the use of array #include <stdio.h> int main() { // array declaration and initialization int arr[5] = { 10, 20, 30, 40, 50 }; // modifying element at index 2 arr[2] = 100; // traversing array using for loop printf("Elements in Array: "); for (int i = 0; i < 5; i++) { printf("%d ", arr[i]); } return 0; } Out Put: Elements in Arraya: 10 20 100 40 50
  • 39. C Pointers Pointers are one of the core components of the C programming language. A pointer can be used to store the memory address of other variables, functions, or even other pointers. The use of pointers allows low-level memory access, dynamic memory allocation, and many other functionality in C. What is a Pointer in C? A pointer is defined as a derived data type that can store the address of other C variables or a memory location. We can access and manipulate the data stored in that memory location using pointers. As the pointers in C store the memory addresses, their size is independent of the type of data they are pointing to. This size of pointers in C only depends on the system architecture. Syntax of C Pointers The syntax of pointers is similar to the variable declaration in C, but we use the ( * ) dereferencing operator in the pointer declaration. datatype * ptr; where •ptr is the name of the pointer. •datatype is the type of data it is pointing to. The above syntax is used to define a pointer to a variable. We can also define pointers to functions, structures, etc.
  • 40. C Pointers How to Use Pointers? The use of pointers in C can be divided into three steps: 1. Pointer Declaration 2. Pointer Initialization 3. Pointer Dereferencing 1. Pointer Declaration In pointer declaration, we only declare the pointer but do not initialize it. To declare a pointer, we use the ( * ) dereference operator before its name. Example int *ptr; The pointer declared here will point to some random memory address as it is not initialized. Such pointers are called wild pointers.
  • 41. C Pointers 2. Pointer Initialization Pointer initialization is the process where we assign some initial value to the pointer variable. We generally use the ( &: ampersand ) addressof operator to get the memory address of a variable and then store it in the pointer variable. Example int var = 10; int * ptr; ptr = &var;We can also declare and initialize the pointer in a single step. This method is called pointer definition as the pointer is declared and initialized at the same time. Example int *ptr = &var;Note: It is recommended that the pointers should always be initialized to some value before starting using it. Otherwise, it may lead to number of errors.
  • 42. C Pointers 3. Pointer Dereferencing Dereferencing a pointer is the process of accessing the value stored in the memory address specified in the pointer. We use the same ( * ) dereferencing operator that we used in the pointer declaration. Dereferencing a Pointer in C
  • 43. C Pointers C Pointer Example // C program to illustrate Pointers #include <stdio.h> void geeks() { int var = 10; int* ptr; // declare pointer variable // note that 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() { geeks(); return 0; } Output :Value at ptr = 0x7ffca84068dc Value at var = 10 Value at *ptr = 1
  • 44. C Pointers Size of Pointers in C The size of the pointers in C is equal for every pointer type. The size of the pointer does not depend on the type it is pointing to. It only depends on the operating system and CPU architecture. The size of pointers in C is 1. 8 bytes for a 64-bit System 2. 4 bytes for a 32-bit System •The reason for the same size is that the pointers store the memory addresses, no matter what type they are. •As the space required to store the addresses of the different memory locations is the same, the memory required by one pointer type will be equal to the memory required by other pointer types. Example: printf("Size of Integer Pointer t:t%d bytesn", sizeof(ptr_int)); printf("Size of Character Pointert:t%d bytesn", sizeof(ptr_char)); printf("Size of Structure Pointert:t%d bytesn", sizeof(ptr_str)); printf("Size of Function Pointert:t%d bytesn", sizeof(ptr_func)); printf("Size of NULL Void Pointert:t%d bytes", sizeof(ptr_vn));
  • 45. C Pointers Types of Pointers in C Pointers in C can be classified into many different types based on the parameter on which we are defining their types. If we consider the type of variable stored in the memory location pointed by the pointer, then the pointers can be classified into the following types: 1. Integer Pointers As the name suggests, these are the pointers that point to the integer values. Syntax int *ptr; These pointers are pronounced as Pointer to Integer. Similarly, a pointer can point to any primitive data type. It can point also point to derived data types such as arrays and user-defined data types such as structures. 2. Array Pointer Pointers and Array are closely related to each other. Even the array name is the pointer to its first element. They are also known as Pointer to Arrays. We can create a pointer to an array using the given syntax. Syntax char *ptr = &array_name; Pointer to Arrays exhibits some interesting properties which we discussed later in this article.
  • 46. C Pointers 3. Structure Pointer The pointer pointing to the structure type is called Structure Pointer or Pointer to Structure. It can be declared in the same way as we declare the other primitive data types. Syntax struct struct_name *ptr; In C, structure pointers are used in data structures such as linked lists, trees, etc. 4. Function Pointers Function pointers point to the functions. They are different from the rest of the pointers in the sense that instead of pointing to the data, they point to the code. Let’s consider a function prototype – int func (int, char), the function pointer for this function will be Syntax int (*ptr)(int, char); Note: The syntax of the function pointers changes according to the function prototype.
  • 47. C Pointers 5. Double Pointers In C language, we can define a pointer that stores the memory address of another pointer. Such pointers are called double-pointers or pointers-to-pointer. Instead of pointing to a data value, they point to another pointer. Syntax datatype ** pointer_name; Dereferencing Double Pointer *pointer_name; // get the address stored in the inner level pointer **pointer_name; // get the value pointed by inner level pointer Note: In C, we can create multi-level pointers with any number of levels such as – ***ptr3, ****ptr4, ******ptr5 and so on.
  • 48. C Pointers 6. NULL Pointer The Null Pointers are those pointers that do not point to any memory location. They can be created by assigning a NULL value to the pointer. A pointer of any type can be assigned the NULL value. Syntax data_type *pointer_name = NULL; or pointer_name = NULL It is said to be good practice to assign NULL to the pointers currently not in use. 7. Void Pointer The Void pointers in C are the pointers of type void. It means that they do not have any associated data type. They are also called generic pointers as they can point to any type and can be typecasted to any type. Syntax void * pointer_name; One of the main properties of void pointers is that they cannot be dereferenced.
  • 49. C Pointers 8. Wild Pointers The Wild Pointers are pointers that have not been initialized with something yet. These types of C-pointers can cause problems in our programs and can eventually cause them to crash. If values is updated using wild pointers, they could cause data abort or data corruption. Example int *ptr; char *str; 9. Constant Pointers In constant pointers, the memory address stored inside the pointer is constant and cannot be modified once it is defined. It will always point to the same memory address. Syntax data_type * const pointer_name; 10. Pointer to Constant The pointers pointing to a constant value that cannot be modified are called pointers to a constant. Here we can only access the data pointed by the pointer, but cannot modify it. Although, we can change the address stored in the pointer to constant. Syntax const data_type * pointer_name;
  • 50. C Pointers Other Types of Pointers in C: There are also the following types of pointers available to use in C apart from those specified above: Far pointer: A far pointer is typically 32-bit that can access memory outside the current segment. Dangling pointer: A pointer pointing to a memory location that has been deleted (or freed) is called a dangling pointer. Huge pointer: A huge pointer is 32-bit long containing segment address and offset address. Complex pointer: Pointers with multiple levels of indirection. Near pointer: Near pointer is used to store 16-bit addresses means within the current segment on a 16-bit machine. Normalized pointer: It is a 32-bit pointer, which has as much of its value in the segment register as possible. File Pointer: The pointer to a FILE data type is called a stream pointer or a file pointer.
  • 51. C Pointers pointer expressions and address arithmetic: 1. Pointer Expression: A pointer is a variable that stores the memory address of another variable. Pointer expressions allow us to perform operations on these pointers. For example, consider the following expression: int *ptr = &var; // ptr stores the address of var Here, ptr is a pointer to an integer variable var. Common pointer operations include dereferencing (using *ptr to access the value at the address) and assigning addresses.
  • 52. C Pointers 2. Address Arithmetic: Pointers can be used in arithmetic operations to navigate through memory. C supports pointer arithmetic, allowing you to move a pointer across memory locations: Increment (ptr + 1): Moves the pointer to the next memory location (depends on the data type size). For example, if ptr points to an integer, ptr + 1 moves the pointer to the next integer (which is typically 4 bytes away). Decrement (ptr - 1): Moves the pointer to the previous memory location. Difference (ptr2 - ptr1): Calculates how many elements are between two pointers. Example of Address Arithmetic: int arr[5] = {10, 20, 30, 40, 50}; int *ptr = arr; // ptr points to the first element of the array printf("%dn", *(ptr + 2)); // Output: 30, accessing the third element via pointer arithmetic * In this case, ptr + 2 points to the third element in the array arr. Address arithmetic is useful when working with arrays, structures, and dynamic memory.
  • 53. C Pointers Example : Basic Pointer Expression #include <stdio.h> int main() { int var = 100; int *ptr; // Declare an integer pointer ptr = &var; // Store the address of var in ptr printf("Value of var: %dn", var); // Output: 100 printf("Address of var: %pn", &var); // Output: Address of var printf("Pointer ptr holds address: %pn", ptr); // Output: Same as &var printf("Value at the address ptr is pointing to: %dn", *ptr); // Output: 100 return 0; }
  • 54. C Pointers Example 2: Pointer Arithmetic with Arrays #include <stdio.h> int main() { int arr[5] = {10, 20, 30, 40, 50}; int *ptr = arr; // Points to the first element of the array // Pointer arithmetic to access array elements printf("First element: %dn", *ptr); // Output: 10 printf("Second element: %dn", *(ptr + 1)); // Output: 20 printf("Third element: %dn", *(ptr + 2)); // Output: 30 // Incrementing pointer to move to next element ptr++; // Now ptr points to the second element printf("Value after ptr++: %dn", *ptr); // Output: 20 return 0; } •ptr + 1 moves the pointer to the next element in the a • we can assign arr[1] = ptr [1 ]
  • 55. C Pointers C Pointer Example // C program to illustrate Pointers #include <stdio.h> void geeks() { int var = 10; int* ptr; // declare pointer variable // note that 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() { geeks(); return 0; } Output :Value at ptr = 0x7ffca84068dc Value at var = 10 Value at *ptr = 1
  • 56. Array and Pointers The relationship between arrays and pointers in C is close, but they are not the same thing. Here's a brief explanation: 1. Arrays as Pointers The name of an array (e.g., arr) acts like a pointer to its first element. For example, if you declare int arr[3] = {10, 20, 30};, then arr is equivalent to &arr[0] * You can use a pointer to access array elements:c int *ptr = arr; // ptr points to arr[0] printf("%dn", *ptr); // Outputs 10 2.Pointer Arithmetic with Arrays You can use pointer arithmetic to traverse an array.c printf("%dn", *(arr + 1)); // Outputs 20 (equivalent to arr[1]) 3. Differences Between Arrays and Pointers Fixed Size: Arrays have a fixed size and cannot be reassigned.c int arr[5]; // Size is fixed Reassignable: Pointers are variables that can point to different memory addresses.c int num = 5; int *p = &num; p = arr; // Pointer can be reassigned Arrays are contiguous blocks of memory . Arrays can't be resized or reassigned, but pointers can. sizeof(arr) gives the total size of the array, while sizeof(ptr) gives the size of the pointer (not the size of what it points to).
  • 57. Array as a Function Argument When you pass an array as a function argument in C, what actually gets passed is a pointer to the first element of the array, not the entire array itself. Key Points: Array Decays to Pointer: When an array is passed to a function, it "decays" into a pointer to its first element. For example, if you pass arr to a function, it is treated as &arr[0]. Function Declaration: You can declare the function parameter as either an array or a pointer; both mean the same thing:c Copy code void printArray(int arr[], int size); // Treated as a pointer void printArray(int *arr, int size); // Equivalent declaration Why Only the Pointer Gets Passed: Passing the entire array would be inefficient because arrays can be large. Instead, only the address of the first element is passed, which is much faster. No Size Information: Since only the pointer is passed, the function doesn't know the size of the array. You need to pass the size as a separate argument.
  • 58. Cont… Example for Array As a function Argument #include <stdio.h> void printArray(int arr[], int size) { for (int i = 0; i < size; i++) { printf("%d ", arr[i]); } printf("n"); } int main() { int numbers[] = {10, 20, 30, 40, 50}; printArray(numbers, 5); // Passing array to function return 0; } Output: 10 20 30 40 50
  • 59. Generic pointer In C, a generic pointer is a special type of pointer that can point to any data type. The type used for generic pointers is void *. Let's break down what a generic pointer is, why it's useful, and how to use it. 1. What is a Generic Pointer (void *)? A generic pointer is declared using the void * type. Unlike other pointers (e.g., int *, char *), a void * pointer does not have an associated data type. It can hold the address of any data type (e.g., int, float, char, structs). 2. Why Use Generic Pointers? Flexibility: They allow you to write functions that can work with any data type. Memory Management: Commonly used in functions like malloc(), calloc(), and free() for dynamic memory allocation, which return or accept a void * pointer. Data Structures: Useful in implementing data structures like linked lists, stacks, or queues that can store any type of data. 3. How to Use Generic Pointers You can assign the address of any type of variable to a void * pointer. However, to access or manipulate the data, you need to cast the void * pointer to the appropriate type.
  • 60. Generic Pointer Example: #include <stdio.h> int main() { int num = 42; float pi = 3.14; void *ptr; // Declare a generic pointer ptr = &num; // Point to an integer printf("Integer value: %dn", *(int *)ptr); // Cast to int * ptr = &pi; // Point to a float printf("Float value: %.2fn", *(float *)ptr); // Cast to float * return 0; } Output: Integer value: 42 Float value: 3.14 * Cannot Dereference Directly: You cannot directly dereference a void * pointer since it doesn't know what type of data it points to. You must cast it to the correct type first. * Type Safety: Using void * pointers can be powerful but also dangerous because the compiler won't check if you're using the correct type. It's up to you to ensure the cast is correct.
  • 61. Null pointer In C, a null pointer is a special type of pointer that doesn't point to any valid memory location. It is used to indicate that the pointer is not currently pointing to any object or function. Let's explore what null pointers are, how they are used, and why they are important. 1. What is a Null Pointer? A null pointer is a pointer that has been assigned a value of NULL. NULL is a macro defined in <stddef.h>, <stdio.h>, <stdlib.h>, or <string.h> as ((void *)0). This means a null pointer points to address 0, which is reserved by the system and cannot be accessed by the user program. 2. Why Use Null Pointers? Indicating Unused Pointers: A null pointer is used to indicate that the pointer does not currently reference a valid memory location. This helps in avoiding accidental dereferencing of uninitialized pointers. Error Handling: Functions that return pointers can use NULL to indicate failure (e.g., malloc() returns NULL if it fails to allocate memory). Linked Data Structures: In data structures like linked lists or trees, null pointers are used to indicate the end of the list or absence of child nodes.
  • 62. Null Pointer Example: #include <stdio.h> int main() { int *ptr = NULL; // Initialize a null pointer if (ptr == NULL) { printf("Pointer is null.n"); } else { printf("Pointer is not null.n"); } return 0; } Output: Pointer is null. Important Points about Null Pointers A null pointer does not point to any valid object or function. It is good practice to initialize pointers to NULL if you don't have a valid address for them initially. Comparing pointers to NULL is a common way to check if they are pointing to valid memory. The constant NULL is typically defined as (void *)0, but you can just use NULL without worrying about the exact definition.
  • 63. Pointer to Pointer In C, a pointer to a pointer (or double pointer) is a type of pointer that stores the address of another pointer. This means it's a pointer that points to another pointer, which in turn points to a data value. 1. What is a Pointer to a Pointer? A pointer to a pointer is declared using two asterisks (**). It can be used to store the address of a pointer variable. Declaration Example: int x = 10; // An integer variable int *ptr = &x; // A pointer to an integer int **ptr2 = &ptr; // A pointer to a pointer 2. Visual Representation Assuming x is stored at address 0x100, ptr is stored at address 0x200, and ptr2 is stored at address 0x300, the memory layout would look like this: 3. Accessing Values Using a Pointer to a Pointer *ptr2 gives you the value stored in ptr (which is the address of x). **ptr2 gives you the value of x. Use Cases for Pointer to Pointer Dynamic Memory Allocation (2D Arrays): They are often used for creating multi-dimensional
  • 64. Pointer to Pointer Use Cases for Pointer to Pointer Dynamic Memory Allocation (2D Arrays): They are often used for creating multi-dimensional arrays dynamically. Function Parameters: They allow functions to modify the original pointers passed to them (e.g., to allocate memory inside a function). Linked Data Structures: Used in linked lists, trees, and other data structures where you need to modify the next pointers Example: #include <stdio.h> int main() { int x = 42; int *ptr = &x; int **ptr2 = &ptr; printf("Value of x: %dn", x); printf("Value of x using *ptr: %dn", *ptr); printf("Value of x using **ptr2: %dn", **ptr2); printf("Address of x: %pn", (void *)&x); printf("Address stored in ptr: %pn", (void *)ptr); printf("Address stored in ptr2: %pn", (void *)ptr2); return 0; } Output: Value of x: 42 Value of x using *ptr: 42 Value of x using **ptr2: 42 Address of x: 0x7ffee4b7482c (example) Address stored in ptr: 0x7ffee4b7482c (example) Address stored in ptr2: 0x7ffee4b74820
  • 65. Dynamic Memory allocation Dynamic memory allocation in C is a way to allocate memory at runtime (i.e., while your program is running) rather than at compile time. This is particularly useful when you don't know the exact amount of memory your program will need before it starts executing. It allows for more flexible and efficient use of memory, especially in situations where data sizes may vary or are determined by user input. Key Concepts of Dynamic Memory Allocation In C, dynamic memory allocation is achieved using several standard library functions defined in <stdlib.h>: 1. malloc() (Memory Allocation) 2. calloc() (Contiguous Allocation) 3. realloc() (Reallocation) 4. free() (Deallocation)
  • 66. Malloc ( ) 1. malloc(): Memory Allocation Purpose: Allocates a block of memory of the specified size (in bytes). Syntax: void *malloc (size_t size); Returns: A pointer to the beginning of the block of memory allocated, or NULL if the allocation fails. Example: int *ptr = (int *)malloc(4 * sizeof(int)); // Allocates memory for 4 integers if (ptr == NULL) { printf("Memory allocation failed.n"); exit(1); }
  • 67. Calloc ( ) 2. calloc(): Contiguous Allocation Purpose: Similar to malloc(), but also initializes the allocated memory to zero. Syntax: void *calloc(size_t num, size_t size); Returns: A pointer to the allocated memory, or NULL if the allocation fails. Example: int *ptr = (int *)calloc(4, sizeof(int)); // Allocates memory for 4 integers, initializes to 0 if (ptr == NULL) { printf("Memory allocation failed.n"); exit(1); }
  • 68. Realloc ( ) 3. realloc(): Reallocation Purpose: Changes the size of previously allocated memory block (using malloc() or calloc()). Syntax: void *realloc(void *ptr, size_t newSize); Returns: A pointer to the newly allocated memory, or NULL if the reallocation fails. If NULL is returned, the original memory block is not freed. Example: ptr = (int *)realloc(ptr, 8* sizeof(int)); // Resizes the memory to fit 8 integers if (ptr == NULL) { printf("Memory reallocation failed.n"); exit(1); }
  • 69. Free ( ) free(): Deallocation Purpose: Frees memory that was previously allocated with malloc(), calloc(), or realloc(). Syntax: void free(void *ptr); Example: free(ptr); // Frees the allocated memory ptr = NULL; // Good practice to set pointer to NULL after freeing
  • 70. Example #include <stdio.h> #include <stdlib.h> int main() { int n; printf("Enter number of elements: "); scanf("%d", &n); int *arr = (int *)malloc(n * sizeof(int)); // Dynamically allocate memory for n integers if (arr == NULL) { printf("Memory allocation failed.n"); return 1; } printf("Enter %d elements:n", n); // Input elements for (int i = 0; i < n; i++) { scanf("%d", &arr[i]); } printf("You entered: "); // Print elements for (int i = 0; i < n; i++) { printf("%d ", arr[i]); } printf("n"); free(arr); // Free allocated memory return 0; } Out Put: Enter number of elements: 3 Enter 3 elements: 5 10 15 You entered: 5 10 15
  • 71. Pointer as a function arguments In C, you can pass pointers as function arguments to allow the function to access and modify variables outside its own scope. This is particularly useful for: Passing large data structures efficiently (like arrays or structures) without copying them. Modifying the values of variables in the calling function. Working with dynamically allocated memory. Let's explore how pointers can be used as function arguments in various ways. Basic Example: Passing a Pointer to a Function Example 1: Using Pointers to Modify Variable Values #include <stdio.h> void updateValue(int *ptr) { // Function that takes a pointer as an argument *ptr = 20; // Dereference the pointer and change the value it points to } int main() { int num = 10; printf("Before: num = %dn", num); updateValue(&num); // Pass the address of num to the function printf("After: num = %dn", num); return 0; } Out Put: Before: num = 10 After: num = 20
  • 72. Example Example: Passing Arrays to Functions #include <stdio.h> void printArray(int *arr, int size) { // Function to print an array for (int i = 0; i < size; i++) { printf("%d ", arr[i]); } printf("n"); } int main() { int numbers[] = {1, 2, 3, 4, 5}; int size = sizeof(numbers) / sizeof(numbers[0]); // Passing the array to the function printArray(numbers, size); return 0; } Out Put: 1 2 3 4 5
  • 73. Dangling Pointer A dangling pointer in C is a pointer that references a memory location that has been freed or deallocated. In other words, it's a pointer that points to memory that is no longer valid. Dangling pointers can lead to undefined behavior, including program crashes, data corruption, or security vulnerabilities. 1. A dangling pointer points to memory that has been freed or is no longer valid. 2. They commonly occur after deallocating memory, returning pointers to local variables, or reassigning pointers. 3. Dangling pointers can cause crashes, data corruption, and security issues. 4. To avoid dangling pointers, always set pointers to NULL after freeing them, avoid returning pointers to local variables, and use tools to detect memory issues.
  • 74. Dangling Pointer #include <stdio.h> #include <stdlib.h> int main() { int *ptr = (int *)malloc(sizeof(int)); // Step 1: Dynamically allocate memory for an integer if (ptr == NULL) { printf("Memory allocation failed.n"); return 1; } *ptr = 42; // Step 2: Assign a value to the allocated memory printf("Value before free: %dn", *ptr); // Outputs: 42 // Step 3: Free the allocated memory free(ptr); // Step 4: ptr is now a dangling pointer (points to freed memory) printf("Value after free (dangling): %dn", *ptr); // Undefined behavior! // Step 5: Avoid dangling pointer by setting it to NULL ptr = NULL; return 0; }
  • 75. Command line Arguments in c In C, command line arguments allow you to pass information to your program when you run it from the terminal (or command prompt). These arguments are provided to the main() function as parameters. Syntax of main() with Command Line Arguments int main(int argc, char *argv[]) * argc (Argument Count): An integer that represents the number of command line arguments passed, including the program's name itself. * argv (Argument Vector): An array of character pointers (strings) that holds all the arguments passed to the program. Key Points argv[0] is the name of the program itself. argv[1] to argv[argc-1] are the actual arguments passed by the user. argc is always at least 1 because it includes the program name.
  • 76. Simple Example: Printing Command Line Arguments #include <stdio.h> int main(int argc, char *argv[]) { printf("Number of arguments: %dn", argc); // Loop through each argument and print it for (int i = 0; i < argc; i++) { printf("Argument %d: %sn", i, argv[i]); } return 0; } How to Run This Program 1. Save the code in a file, e.g., args.c. 2. Compile the code: bash gcc args.c -o args 3. Run the program with command line arguments: bash ./args Hello World 123 Sample Output Number of arguments: 4 Argument 0: ./args Argument 1: Hello Argument 2: World Argument 3: 123