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

Unit-4 LDP

Pointers in C are variables that store memory addresses. They allow direct manipulation of memory and are fundamental to C programming. The document discusses the basics of pointers including declaration, initialization, dereferencing, pointer arithmetic, NULL pointers, their relationship to arrays, passing pointers to functions, dynamic memory allocation using pointers, and pointer to pointer. It also discusses how arrays can decay to pointers in certain contexts like passing arrays to functions, and how functions can return pointer values.

Uploaded by

mailkinghimanshu
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)
27 views

Unit-4 LDP

Pointers in C are variables that store memory addresses. They allow direct manipulation of memory and are fundamental to C programming. The document discusses the basics of pointers including declaration, initialization, dereferencing, pointer arithmetic, NULL pointers, their relationship to arrays, passing pointers to functions, dynamic memory allocation using pointers, and pointer to pointer. It also discusses how arrays can decay to pointers in certain contexts like passing arrays to functions, and how functions can return pointer values.

Uploaded by

mailkinghimanshu
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/ 10

UNIT-4

Pointers and Structures


Basics of pointers
Pointers in C are variables that store memory addresses. They are a fundamental concept in C
programming and provide a way to work with memory directly. Here are the basics of
pointers in C:

1. Declaration and Initialization:


To declare a pointer, you use the * symbol. For example, int *ptr; declares a pointer to an
integer.
Pointers should be initialized before they are used. They can be initialized with the address of
a variable: int x = 10; int *ptr = &x; assigns the address of x to ptr.

2. Accessing the Value (Dereferencing):


To access the value that a pointer points to, you use the * operator. For example, int y = *ptr;
assigns the value pointed to by ptr to y.

3. Pointer Arithmetic:
Pointers can be incremented or decremented, which moves the pointer to the next or previous
memory location of its type. For example:
int arr[5] = {1, 2, 3, 4, 5};
int *ptr = arr; // ptr points to the first element of arr
ptr++; // ptr now points to the second element of arr

4. NULL Pointer:
Pointers can be assigned a special value called NULL which means they are not pointing to
any memory location. It's a good practice to initialize pointers to NULL before assigning
them a valid memory address, to avoid accidental access to undefined memory locations.

5. Pointer and Arrays:


Arrays and pointers are closely related in C. In most contexts, an array name can be used as a
pointer to its first element. For example:
int arr[5] = {1, 2, 3, 4, 5};
int *ptr = arr; // ptr points to the first element of arr

6. Function Pointers:
Pointers can also point to functions, allowing you to create arrays of functions, pass functions
as arguments to other functions, etc. This is an advanced topic but very powerful in certain
situations.

7. Dynamic Memory Allocation:


Pointers are often used with dynamic memory allocation functions like malloc(), calloc(), and
realloc() to allocate memory at runtime. For example:
int *ptr = (int *)malloc(sizeof(int));
*ptr = 10;

8. Passing Pointers to Functions:


Pointers can be passed to functions, allowing functions to modify the values of variables
outside their scope. This is how functions in C can return multiple values.
void modifyValue(int *ptr) {
*ptr = 20;
}
// Usage
int x = 10;
modifyValue(&x); // x is now 20
Remember that working with pointers requires a good understanding of memory management
to avoid issues like segmentation faults and memory leaks. Always ensure that pointers are
properly initialized and dereferenced to valid memory locations to avoid undefined behavior
in your programs.

Pointer to Pointer
A pointer to a pointer in C, also known as a double pointer, is a pointer variable that can hold
the address of another pointer variable. This concept is particularly useful when working with
multi-dimensional arrays or when dealing with dynamic memory allocation.

Declaration of Pointer to Pointer:


int **ptr2ptr;
This declares a double pointer to an integer. ptr2ptr can store the address of a pointer
variable that points to an integer.

Initialization of Pointer to Pointer:


int x = 10;
int *ptr1 = &x;
int **ptr2ptr = &ptr1;
Here, ptr2ptr is a pointer to a pointer. It points to the address of ptr1, which, in turn, points to
the address of the integer variable x.
Accessing Values using Pointer to Pointer:
int x = 10;
int *ptr1 = &x;
int **ptr2ptr = &ptr1;
This accesses the value pointed to by the pointer ptr1, which is the address stored in
ptr2ptr. In this case, value would be 10, the value of the integer variable x .

Use Cases of Pointer to Pointer:


Dynamic Memory Allocation: Pointer to pointer is often used in dynamic memory
allocation scenarios where you have an array of pointers. Each element of the array is a
pointer pointing to dynamically allocated memory blocks.
int **matrix;
matrix = (int **)malloc(rows * sizeof(int *));
for(int i = 0; i < rows; i++) {
matrix[i] = (int *)malloc(columns * sizeof(int));
}

Function Arguments: Pointer to pointer can be used when you want to modify the original
pointer inside a function
void modifyPointer(int **ptr) {
*ptr = (int *)malloc(sizeof(int));
**ptr = 42;
}

// Usage
int *ptr;
modifyPointer(&ptr);
Multi-dimensional Arrays: Pointer to pointer is useful for dynamically allocating memory
for a 2D array.
cCopy code
int rows = 3, columns = 4; int **matrix = (int **)malloc(rows * sizeof(int *)); for(int i = 0; i
< rows; i++) { matrix[i] = (int *)malloc(columns * sizeof(int)); }
Remember, when using pointer to pointer, you need to be careful with memory management
to avoid memory leaks. Always free the memory allocated dynamically when it is no longer
needed using the free() function.

pointer to array
A pointer to an array can be used to access the elements of an array. When you declare an
array, the name of the array represents the memory address of the first element of the array.
Therefore, a pointer to an array is essentially a pointer to the first element of the array. Here's
how you can use pointers to access and manipulate arrays in C:
1. Pointer to the First Element of an Array:
int arr[5] = {1, 2, 3, 4, 5};
int *ptr = arr; // ptr points to the first element of arr
In this example, ptr is a pointer that points to the first element of the arr array.
2. Accessing Array Elements using Pointers:
You can use pointer arithmetic to access array elements:
int firstElement = *ptr; // Accesses the first element of the array (same as arr[0])
int thirdElement = *(ptr + 2); // Accesses the third element of the array (same as arr[2])
3. Looping Through an Array using Pointers:
You can use a pointer to iterate through an array:
int *ptr = arr;
for (int i = 0; i < 5; ++i) {
printf("%d ", *(ptr + i));
}
// Output: 1 2 3 4 5
4. Pointer Arithmetic with Arrays:
Pointers and arrays in C are closely related. When you perform pointer arithmetic, the
compiler automatically scales the offset based on the size of the data type.
For example:
int arr[5] = {1, 2, 3, 4, 5};
int *ptr = arr; // ptr points to the first element of arr

printf("%d\n", *(ptr + 1)); // Output: 2


printf("%d\n", *(arr + 1)); // Output: 2 (arr is treated as a pointer to its first element)
printf("%d\n", arr[1]); // Output: 2 (standard array access)
All three lines in the example above access the second element of the array.
5. Passing an Array to a Function:
When you pass an array to a function, you are actually passing a pointer to the first element
of the array. For example:
void printArray(int *arr, int size) {
for (int i = 0; i < size; ++i) {
printf("%d ", arr[i]);
}
}

int main() {
int arr[5] = {1, 2, 3, 4, 5};
printArray(arr, 5);
// Output: 1 2 3 4 5
return 0;
}
In the printArray function, arr is a pointer to the first element of the array passed from the
main function.

array to pointer
An array can decay into a pointer to its first element in certain contexts. This means that
when you use the name of an array in an expression, it is automatically converted to a pointer
to the first element of the array. Here's how it works:
1. Array to Pointer Conversion:
When you declare an array:
int arr[5] = {1, 2, 3, 4, 5};
The name arr represents the memory address of the first element of the array. So, arr can be
used wherever a pointer to an integer is expected.
2. Using Array Name as a Pointer:
You can use the array name as a pointer to its first element:
int *ptr = arr; // ptr points to the first element of arr
In this case, ptr is a pointer that points to the first element of the arr array.
3. Passing an Array to a Function:
When you pass an array to a function, you're actually passing a pointer to the first element of
the array. For example:
void printArray(int *arr, int size) {
for (int i = 0; i < size; ++i) {
printf("%d ", arr[i]);
}
}
int main() {
int arr[5] = {1, 2, 3, 4, 5};
printArray(arr, 5);
// Output: 1 2 3 4 5
return 0;
}
In the printArray function, arr is treated as a pointer to the first element of the array passed
from the main function.
4. Array Name in Expressions:
When used in most expressions, the array name decays into a pointer to its first element:
int x = arr[2]; // Accesses the third element of the array using array subscript notation
int y = *(arr + 2); // Accesses the third element of the array using pointer arithmetic
Both arr[2] and *(arr + 2) access the third element of the array arr.
5. Array as Function Argument:
Arrays are commonly passed to functions as pointers:
void modifyArray(int *arr, int size) {
for (int i = 0; i < size; ++i) {
arr[i] *= 2;
}
}

int main() {
int arr[5] = {1, 2, 3, 4, 5};
modifyArray(arr, 5);
// arr now contains: 2 4 6 8 10
return 0;
}
In the modifyArray function, arr is treated as a pointer to its first element. Any changes made
to arr inside the function are reflected in the original array.
Remember that this array-to-pointer decay applies in most contexts, but not all. For instance,
sizeof(arr) still gives you the size of the whole array, not the size of a pointer.

Function returning pointer.


functions can return pointers to various types, including pointers to basic data types, arrays,
or even structures. Here's how you can declare and define a function that returns a pointer in
C:
1. Function Returning Pointer to Basic Data Type:
#include <stdio.h>

int* createInt() {
int *ptr = (int *)malloc(sizeof(int));
*ptr = 42;
return ptr;
}

int main() {
int *numPtr = createInt();
printf("Value: %d\n", *numPtr); // Output: Value: 42
free(numPtr); // Don't forget to free the allocated memory
return 0;
}
In this example, the createInt function allocates memory for an integer, assigns a value of 42
to it, and returns a pointer to the allocated memory. The main function calls createInt and
prints the value.
2. Function Returning Pointer to Array:
#include <stdio.h>

int* createArray(int size) {


int *arr = (int *)malloc(size * sizeof(int));
for (int i = 0; i < size; ++i) {
arr[i] = i * 2;
}
return arr;
}

int main() {
int size = 5;
int *arrPtr = createArray(size);
for (int i = 0; i < size; ++i) {
printf("%d ", arrPtr[i]); // Output: 0 2 4 6 8
}
free(arrPtr); // Don't forget to free the allocated memory
return 0;
}
In this example, the createArray function dynamically allocates memory for an array of
integers, initializes it, and returns a pointer to the first element of the array.
3. Function Returning Pointer to String:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char* createString(const char* input) {
char *str = (char *)malloc(strlen(input) + 1);
strcpy(str, input);
return str;
}

int main() {
const char *text = "Hello, World!";
char *strPtr = createString(text);
printf("String: %s\n", strPtr); // Output: String: Hello, World!
free(strPtr); // Don't forget to free the allocated memory
return 0;
}
In this example, the createString function dynamically allocates memory for a string, copies
the input string into the allocated memory, and returns a pointer to the first character of the
new string.
When using functions that return pointers, it's crucial to manage memory properly.
Remember to deallocate the memory using the free function once you are done using the data
to prevent memory leaks.

You might also like