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

Pointer

The document provides a comprehensive overview of pointers in C programming, including their definition, syntax for declaration, dereferencing, and pointer arithmetic. It also covers the relationship between arrays and pointers, dynamic memory allocation using functions like malloc and calloc, and the importance of managing memory with free. Examples are provided to illustrate each concept, demonstrating how pointers can be used to manipulate data and memory effectively.

Uploaded by

santoshpyaku
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)
3 views

Pointer

The document provides a comprehensive overview of pointers in C programming, including their definition, syntax for declaration, dereferencing, and pointer arithmetic. It also covers the relationship between arrays and pointers, dynamic memory allocation using functions like malloc and calloc, and the importance of managing memory with free. Examples are provided to illustrate each concept, demonstrating how pointers can be used to manipulate data and memory effectively.

Uploaded by

santoshpyaku
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/ 36

Pointer

• Pointer address, dereference, declaration, assignment, initialization


• Pointer Arithmetic
• Array and Pointer
Prepared By: Santosh Pyakurel

1
Definition
• A pointer variable is a variable that holds the memory address of
another variable. In C, pointers are used to directly access and
manipulate memory locations. The type of pointer must correspond
to the type of data it points to.
• Used to change variables inside a function (reference parameters)
• Used to remember a particular member of a group (such as an
array)
• Used in dynamic (on-the-fly) memory allocation (especially of
arrays)
• Used in building complex data structures (linked lists, stacks,
queues, trees, etc.)

2
Syntax for declaring a pointer:
type *pointer name;

Following are some examples of declaring a pointer in C:


int *ptr; //pointer to int
float *ptr; //pointer to float
char *ptr; //pointer to char
double *ptr; //pointer to double

Just like a variable, pointer is declared in the same way, just with an additional
pointer operator *.

3
Assigning Value to a Pointer #include<stdio.h>
Variable. int main(void)
When we declare a pointer, it {
contains garbage value, which
means it could be pointing int a = 10;
anywhere in the memory. Pointer int *ptr; //declare a pointer
Initialization is the process of ptr = &a; // assign value to pointer
assigning the address of a variable
to a pointer. In C language, the printf("Address pointed by ptr is: %p \n", ptr);
address operator & is used to return 0;
determine the address of a
variable. The & (immediately }
preceding a variable name)
returns the address of the
variable associated with it.

4
Dereferencing
Dereferencing a pointer means accessing the value stored at the memory address
the pointer is pointing to. Use the dereference operator (*).
Once the pointer is assigned a valid address, you can dereference it to access or
modify the value at that address.
#include<stdio.h>
int main(){
int x = 10;
int *p = &x; // p points to x
printf("Value of x: %d\n", *p);
// Dereferencing p to get the value of x
return 0;
}

5
Full Example Combining All Concepts
#include <stdio.h>
int main() {

int x = 42; // A regular integer variable


int *p = &x; // Declaration and initialization of a pointer
printf("Address of x: %p\n", p); // Pointer address
printf("Value of x: %d\n", *p); // Dereference to access x's value
*p = 50; // Modify x's value through the pointer
printf("New value of x: %d\n", x); // x is updated to 50
return 0;
}

6
Output:
Address of x: 0x7ffee3c28abc (example address)
Value of x: 42
New value of x: 50

7
Null Pointer
When we assign NULL to a pointer, it means that it does not point to
any valid address. NULL denotes the value 'zero’.
Example :
int *ptr=0;
The above code will initialize the ptr pointer will a null value.
We can also use the NULL macro, which is nothing but a predefined
constant for null pointer. This is defined in the <stdio.h> header library.
int *ptr = NULL;
• Always initialize pointers to NULL if you aren't assigning a memory address
immediately.
• Check if a pointer is NULL before dereferencing.
• Avoid using magic numbers like 0—use the NULL macro for clarity.

8
#include <stdio.h>
int main() {
// Null pointer initialization
int *ptr = NULL;
int num = 10;
ptr = &num;
printf("Value of num: %d\n", *ptr);
return 0;
}

9
Pointer Arithmetic
• Pointer arithmetic works by moving the pointer forward or backward in memory in
increments based on the size of the data type it is pointing to. For example, if a pointer is
pointing to an int, and the size of int is 4 bytes, incrementing the pointer by 1 will move it
by 4 bytes.
• C supports four arithmetic operators that can be used with pointers
• +,-,++,--
• All pointers will increase or decrease by the length of the data type they point to.
• Pointer arithmetic is commonly used with arrays. The compiler stores array elements in
contiguous memory locations, and pointer arithmetic allows you to efficiently access
these elements.
Basic operations you can perform with pointers
➢Increment (++): Move the pointer forward to the next element of the same type.
➢Decrement (--): Move the pointer backward to the previous element of the same type.
➢Add an integer (+): Move the pointer forward by a specified number of elements.
➢Subtract an integer (-): Move the pointer backward by a specified number of elements.

10
#include <stdio.h>
int main() {
int a = 10, b = 20, c = 30;
int *ptr;
ptr = &a;
printf("Value of a: %d\n", *ptr);
ptr = ptr + 1; //ptr++
printf("Value after pointer + 1: %d\n", *ptr);
ptr = ptr + 1; //ptr++
printf("Value after pointer + 1: %d\n", *ptr);
return 0;
}

11
#include <stdio.h>

int main() {
int arr[3] = {10, 20, 30};
int *ptr;
ptr = &arr[0];
printf("Value of a: %d\n", *ptr);
ptr = ptr + 1;
printf("Value after pointer + 1: %d\n", *ptr);
ptr = ptr + 1;
printf("Value after pointer + 1: %d\n", *ptr);
return 0;
}

12
Example of Dereferencing and Adding Values:
#include <stdio.h>
int main() {
int a = 10, b = 20, sum;
int *ptr1, *ptr2;
ptr1 = &a;
ptr2 = &b;
sum = *ptr1 + *ptr2;
printf("Value of *ptr1: %d\n", *ptr1);
printf("Value of *ptr2: %d\n", *ptr2);
printf("Sum of *ptr1 and *ptr2: %d\n", sum);
return 0;
}
13
Array and Pointer
• In C, the name of an array acts like a pointer to its first element. So,
arr (an array) is essentially a pointer to the first element arr[0].
int arr[5];
int *ptr = arr; // arr is a pointer to the first element

Accessing Array Elements with Pointers:


You can use pointer arithmetic to access array elements.
• *arr = 10; // Equivalent to arr[0] = 10
• *(arr + 1) = 20; // Equivalent to arr[1] = 20

14
Using Arrays and Pointers Together
#include <stdio.h>
int main() {
int arr[3] = {1, 2, 3};
int *ptr = arr;
// Accessing array elements using pointer
printf("First element: %d\n", *ptr); // Equivalent to arr[0]
printf("Second element: %d\n", *(ptr + 1)); // Equivalent to arr[1]
printf("Third element: %d\n", *(ptr + 2)); // Equivalent to arr[2]
return 0;
}

15
Pointer Arithmetic in Array
#include <stdio.h>
int main() {
int arr[5] = {10, 20, 30, 40, 50};
int *ptr = arr;
printf("Incrementing pointer:\n");
printf("Initial ptr value (ptr points to arr[0]): %d\n", *ptr);
ptr++;
printf("After incrementing ptr: %d\n", *ptr);
printf("\nDecrementing pointer:\n");
ptr--; // Move back to arr[0]
printf("After decrementing ptr: %d\n", *ptr); // Now points to arr[0]
printf("\nAdding 2 to the pointer (ptr + 2):\n");
ptr = arr; // Reset pointer to the start
ptr = ptr + 2; // Move pointer to arr[2]
printf("ptr + 2 points to: %d\n", *ptr); 16
printf("\nSubtracting 1 from the pointer (ptr - 1):\n");
ptr = ptr - 1; // Move pointer back to arr[1]
printf("ptr-1 points to: %d\n", *ptr); // Now points to arr[1]
return 0;
}
Output:
Incrementing pointer:
Initial ptr value (ptr points to arr[0]): 10
After incrementing ptr: 20
Decrementing pointer:
After decrementing ptr: 10
Adding 2 to the pointer (ptr + 2):
ptr + 2 points to: 30
Subtracting 1 from the pointer (ptr - 1):
ptr - 1 points to: 20

17
WAP to input data of array from user, display value by using
pointer and change the value through pointer.
#include <stdio.h>
int main() {
int size=10, i;
int arr[size];
int *ptr = arr;
printf("Enter the elements of the array:\n"); // Input values into the array
for ( i = 0; i < size; i++) {
printf("Element %d: ", i + 1);
scanf("%d", ptr + i);
}

printf("\nArray values using pointer:\n");


for (i = 0; i < size; i++) {
printf("Element %d: %d\n", i + 1, *(ptr + i));
} 18
// Modify the values of the array using pointer
int indexToChange, newValue;
printf("\nEnter the index to change (1 to %d): ", size);
scanf("%d", &indexToChange);
printf("Enter the new value: ");
scanf("%d", &newValue);
*(ptr + (indexToChange - 1)) = newValue; // Update the array value through pointer

printf("\nUpdated array values:\n");


for ( i = 0; i < size; i++) {
printf("Element %d: %d\n", i + 1, *(ptr + i));
}
return 0;
}

19
Pointer in String
In C, a pointer to a string is simply a pointer to the first character of the string
(which is an array of characters). Strings in C are null-terminated arrays of
characters, meaning that the last character in the string is \0.
Example:
#include <stdio.h>
int main() {
char str[] = "Hello, World!";
char *ptr = str; // Declare a pointer to the string

while (*ptr != '\0') { // While not at the end of the string


printf("%c ", *ptr);
ptr++;
}
return 0;
20
}
Explanation:
• char str[] = "Hello, World!"; defines a string.
• char *ptr = str;creates a pointer to the first character of the
string.
• The loop while (*ptr != '\0') iterates over the string,
dereferencing the pointer *ptr to access each character until
it reaches the null terminator \0.

21
Passing Strings to Functions Using Pointers
#include <stdio.h>

void printString(char *s) {


while (*s) {
printf("%c", *s);
s++;
}
printf("\n");
}

int main() {
char str[] = "Pointers!";
printString(str);
return 0;
}

22
Dynamic Memory Allocation in C using
malloc(), calloc(), free() and realloc()
Dynamic memory allocation in C allows a program to allocate memory
during runtime, rather than at compile time. This is useful when the
amount of memory needed is not known in advance or when the
memory requirements vary. The C standard library provides several
functions for dynamic memory allocation, primarily in the <stdlib.h>
header.

23
• C Dynamic Memory Allocation can be defined as a procedure in
which the size of a data structure (like Array) is changed during
the runtime.
C provides some functions to achieve these tasks. There are 4
library functions provided by C defined under <stdlib.h> header
file to facilitate dynamic memory allocation in C programming.
They are:
1.malloc()
2.calloc()
3.free()
4.realloc()
24
malloc()
• The malloc() function in C is used for dynamic memory allocation. It
allocates a block of memory of the specified size and returns a pointer to
the first byte of the allocated memory. If the memory allocation fails, it
returns NULL.
• Syntax of malloc() in C:
ptr = (cast-type*) malloc(byte-size)
For Example: ptr = (int*) malloc(100 *sizeof(int));

Since the size of int is 4 bytes, this statement will allocate 400 bytes
of memory. And, the pointer ptr holds the address of the first byte in
the allocated memory.
➢ptr is cast-type pointer. i.e int *ptr

25
26
#include <stdio.h>
#include <stdlib.h>
int main()
{
int *ptr;
int n, i;
printf("Enter number of elements:");
scanf("%d",&n); // Get the number of elements for the array
printf("Entered number of elements: %d\n", n);
ptr = (int*)malloc(n * sizeof(int)); // Dynamically allocate memory using malloc()

// Check if the memory has been successfully allocated by malloc or not

27
if (ptr == NULL) {
printf("Memory not allocated.\n");
exit(0);
} else {
printf("Memory successfully allocated using malloc.\n");
// Get the elements of the array
for (i = 0; i < n; ++i) {
ptr[i] = i + 1;
}
printf("The elements of the array are: ");
for (i = 0; i < n; ++i) {
printf("%d, ", ptr[i]);
}}
free(ptr);
return 0;
}
28
calloc()
“calloc” or “contiguous allocation” method in C is used to dynamically allocate the
specified number of blocks of memory of the specified type. it is very much similar
to malloc() but has two different points and these are:
1. It initializes each block with a default value ‘0’.
2.It has two parameters or arguments as compare to malloc().
Syntax of calloc() in C : int * ptr = (cast-type*)calloc(n, element-size);
here, n is the no. of elements and element-size is the size of each element.
Example:
ptr = (float*) calloc(25, sizeof(float));

This statement allocates contiguous


Space in memory for 25 elements
each with the size of the float.

29
#include <stdio.h>
#include <stdlib.h>
int main(){
int *ptr;
int n=5, i;
printf("Enter number of elements: %d\n", n);
ptr = (int*)calloc(n, sizeof(int));

if (ptr == NULL) {
printf("Memory not allocated.\n");
exit(0);
}

30
else {
printf("Memory successfully allocated using calloc.\n");
// Get the elements of the array
for (i = 0; i < n; ++i) {
ptr[i] = i + 1;
}

printf("The elements of the array are: ");


for (i = 0; i < n; ++i) {
printf("%d ", ptr[i]);
}
}
free(ptr);
return 0;
}
31
C free()

In C is used to dynamically de-allocate the memory. The memory allocated using


functions malloc() and calloc() is not de-allocated on their own. Hence the free()
method is used, whenever the dynamic memory allocation takes place. It helps
to reduce wastage of memory by freeing it.
• Syntax of free() in C : free(ptr);

32
realloc()
• “realloc” or “re-allocation” method in C is used to dynamically change the
memory allocation of a previously allocated memory. In other words, if the
memory previously allocated with the help of malloc or calloc is insufficient,
realloc can be used to dynamically re-allocate memory. re-allocation of
memory maintains the already present value and new blocks will be
initialized with the default garbage value.

• Syntax of realloc() in C: ptr = realloc(ptr, newSize);


where ptr is reallocated with new size 'newSize'.

33
34
#include <stdio.h>
#include <stdlib.h>
int main(){
int* ptr;
int n=5, i;
ptr = (int*)calloc(n, sizeof(int));
if (ptr == NULL) {
printf("Memory not allocated.\n");
exit(0);
} else {
printf("Memory successfully allocated .\n");
for (i = 0; i < n; ++i) {
ptr[i] = i + 1;

}
printf("The elements of the array are: ");
for (i = 0; i < n; ++i) {
printf("%d ", ptr[i]);
}
35
n = 10;
ptr = (int*)realloc(ptr, n * sizeof(int)); // Dynamically re-allocate memory using realloc()
if (ptr == NULL) {
printf("Reallocation Failed\n");
exit(0); }
// Get the new elements of the array
for (i = 5; i < n; ++i) {
ptr[i] = i + 1;
}
printf(“\nThe elements of the array are: ");
for (i = 0; i < n; ++i) {
printf("%d ", ptr[i]);
}
free(ptr);
}
return 0;
36
}

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy