0% found this document useful (0 votes)
2 views39 pages

CPPS Unit 3 Pointers

This document provides an overview of pointers in C programming, including their definition, declaration, initialization, and usage for accessing values and array elements. It covers key concepts such as pointer arithmetic, dereferencing, and the differences between variables and pointers, along with example programs. Additionally, it discusses the advantages and disadvantages of using pointers in programming.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views39 pages

CPPS Unit 3 Pointers

This document provides an overview of pointers in C programming, including their definition, declaration, initialization, and usage for accessing values and array elements. It covers key concepts such as pointer arithmetic, dereferencing, and the differences between variables and pointers, along with example programs. Additionally, it discusses the advantages and disadvantages of using pointers in programming.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 39

UNIT – III

Pointers: Definition and declaration and initialization of


pointers. Accessing values using pointers. Accessing array
elements using pointers.

Functions: Definition and declaration. Built-in functions


and User-defined functions. Categories of functions with
example. Pointers as function arguments, array as
function argument, Call-by-value and call-by-reference.
Recursion.
C Pointer
• In C programming, a variable is a named storage
location in memory that holds a value which can be
changed during program execution.
• Example: int age=25;
• In C programming, a pointer is a variable that stores
the memory address of another variable.
• Syntax-datatype *pointer_name;
• Example- int x = 10;
int *ptr = &x;
•x is a normal integer variable.
•&x gives the address of x.
•ptr is a pointer to int, and it stores the address of x.
•The * symbol is used to declare a pointer and also to dereference it
(access the value it points to).
•The & symbol is used to get the address of a variable.
Declaration Types:
 Type1:int* myNum;
 Type2:int *myNum;
• Technically, both are the same — both declare myNum as a pointer to an int.
• but they can behave differently when declaring
multiple pointers in one line, which is where the confusion comes in.
 Example:
int* a, b;
is the same as:
int *a;
int b;
• If you want to declare two pointers ,it is also recdommended to do as
int *a,int *b;
Example Program

#include <stdio.h>

int main() {
int x = 10; // Normal integer variable
int *ptr; // Pointer to integer

ptr = &x; // ptr stores the address of x

printf("Value of x: %d\n", x);


printf("Address of x: %p\n", &x);
printf("Value of ptr (address of x): %p\n", ptr);
printf("Value pointed to by ptr: %d\n", *ptr); // Dereferencing pointer

return 0;
}
Important Points
1."A pointer is a derived data type that can
store the address of other variables or a
memory location."
✅ This means a pointer doesn't store data
directly, but rather stores the memory address
of another variable.
Example:
int x = 5;
int *ptr = &x; // ptr stores the address of x
2."Pointers allow us to access and modify the
data stored at a specific memory location.“

✅ By using the dereferencing operator *, we can


access or modify the value stored at the address a
pointer holds.
 Example:
*ptr = 20; // changes the value of x to 20
3."As the pointers in C store the memory
addresses, their size is independent of the type
of data they are pointing to.“
✅ The size of a pointer depends on the
architecture of the system, not on the data
type it points to.
Example:
int *p1;
char *p2;
float *p3;
Even though p1, p2, and p3 point to different data types, they all store memory addresses.
So, they will all have the same size in memory.
Example Program:
#include <stdio.h>

int main() {
int *ptr_int;
char *ptr_char;
float *ptr_float;
double *ptr_double;

printf("Size of int pointer: %zu bytes\n", sizeof(ptr_int));


printf("Size of char pointer: %zu bytes\n", sizeof(ptr_char));
printf("Size of float pointer: %zu bytes\n", sizeof(ptr_float));
printf("Size of double pointer: %zu bytes\n", sizeof(ptr_double));

return 0;
}
🧾 Real-Life Example: Contact Book
•.

•You have a contact book on your phone.


•Each contact entry has:
•A name (e.g., John)
•A phone number (e.g., +91-9876543210)
Here:
•The name is like a variable (you can read or update it).
•The phone number is like a pointer — it points to a real person (you can
call them, send a message, etc.).
•You don’t store the actual person — you store their reference/address
(phone number).
How to Use Pointers?

The use of pointers in C can be divided into three steps:

• Pointer Declaration
• Pointer Initialization
• Pointer Dereferencing
1. Pointer Declaration

• A pointer declaration defines the variable that store the memory


address of another variable and use deference operator(*) before
the pointer variable name the but do not initialize it.

Syntax:
datatype *pointer_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.
2. Pointer Initialization

• Pointer initialization is the process to assign some value to the


pointer variable.
• Use the (&) address 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; //ptr now holds the address of var

• Pointer can be declare and initialize in a single step. This method is


called pointer definition as the pointer is declared and initialized at
the same time.
int *ptr = &var;

Note: It is recommended that the pointers should always be initialized


to value before using it. Otherwise, it may lead to number of errors.
3. Pointer Dereferencing

• Dereferencing a pointer is the process of accessing the value


stored in the memory address specified in the pointer.

• Use the same ( * ) dereferencing operator that used in the


pointer declaration.
Variables, addresses
Memory Value Variable at this
int a, b; Address address

int *p1, *p2;


0x1000
a = 11; 0x1004 11 a
0x1008 20 b
b = 20;
0x100C

p1 = &a; 0x1010
0x1014 0x1004 p1
p2 = &b; 0x1018 0x1008 p2
0x101C
MCQ,S
Difference Between Variables And Pointer

Feature Variable Pointer


Stores a value
Definition directly Stores the address of another variable

Declaration int x = 10; int *ptr = &x;

A data value (e.g.,


Holds 10, 20, etc.) A memory address (e.g., 0x100)

Access Just use the Use *ptr to access the value at the
value variable name (x) address

Memory Uses memory to


usage store a value Uses memory to store an address

Symbol * for declaration and dereferencing, &


used None to get address
Declaring a string constant using pointers
char *s1 = “HELLO”;

• ‘s1’ is a pointer variable that points to a character.

• The compiler will allocate space for the string “HELLO”, and copy
the starting address of this space into the variable ‘s1’.

Address 0x100 0x101 0x102 0x103 0x104 0x105


Contents ‘H’ ‘E’ ‘L’ ‘L’ ‘O’ ‘\0’

Variable s1
Address 0x120
Contents 0x100
Example
#include <stdio.h>

int main() {
// String constant using pointer
char *str = "Hello, World!";

// Print the string


printf("String: %s\n", str);

// Print the address stored in str (i.e., address of first character)


printf("Address stored in str (address of 'H'): %p\n", *str);

// Print the value at the address (dereferencing the pointer)

return 0;
}
String using pointers in C

• A string str using char character array of size 6.


char str[6] = "Hello";

• create a character pointer ptr and store the address of the


string str variable in it. This way, ptr will point at the string str.

• assigning the address of the string str to the pointer ptr.


char *ptr = str;
Accessing string via pointer
To access and print the elements of the string we can use a loop and
check for the \0 null character.
Example:

#include <stdio.h>

int main() {
// Declare a string constant using a pointer
// char *str = "Pointer Loop";
char str[6] = "Hello"; // string variable
char *ptr = str;

// Use a loop to access each character


printf("Accessing string using pointer and loop:\n");

while (*ptr != '\0') {


printf("%c ", *ptr); // Print the character
ptr++; // Move pointer to the next character
}

printf("\n");

return 0;
}
Pointers and Arrays
• Pointers are also used to access arrays.
Ex:
int myNumbers[4] = {25, 50, 75, 100} ;

• An array name acts like a pointer constant.


• The value of this pointer constant is the address of the first element
of the array.
• Assign this address to a non-constant pointer of the same type, and
then use that pointer to access the elements of the array.
• To print the memory address of each array element use address
operator(&) for an array:

Note: The last number of each of the elements' memory address is


different, with an addition of 4. It is because the size of an int type is
typically 4 bytes.
Note:
The compiler reserves 4 bytes of memory for each array element, which
means that the entire array takes up 16 bytes (4*4) of memory storage.
How Are Pointers Related to Arrays

• In C, the name of an array, is actually a pointer to the first


element of the array.
• The memory address of the first element is the same as the name
of the array:
int myNumbers[4] = {25, 50, 75, 100};

printf("%p\n", myNumbers) //Get the memory address of


the myNumbers
array

printf("%p\n", &myNumbers[0]); // Get the memory address


of the
first array element

Output:

0x7ffe70f9d8f0
0x7ffe70f9d8f0
• myNumbers is a pointer to the first element in myNumbers,
use the * operator to access the value of the first element.

• To access the rest of the elements in myNumbers, increment


the pointer/array (+1, +2, etc):
Or
• using Loop can access the value of the elements of an array:
Change the value of array elements with pointers:
int myNumbers[4] = {25, 50, 75, 100};

// Change the value of the first element to 13


*myNumbers = 13;

// Change the value of the second element to 17


*(myNumbers +1) = 17;

// Get the value of the first element


printf("%d\n", *myNumbers);

// Get the value of the second element


printf("%d\n", *(myNumbers + 1));

Output:
13 17
Alternate way to use pointer to access array
elements
int arr[10]; /* Declare array ‘arr’ of 10 integers */
int *pa; /* Declare ‘pa’ to be a pointer to a integer */

pa = arr; /* This initializes pointer ‘pa’ to point to the first


element of array ‘arr’ – The name of an array
evaluates to the starting address of the array */
To access the ‘i’th element of array arr, we can use the following
syntax:

int b;
b = pa[i]; /* The pointer variable can be used like the array
name */
Note: pa[i] is same as *(pa+i)
Accessing the elements of the two dimensional array
via a simple pointer

In the following code,


• Printing the content of the num array
using for loop and by incrementing
the value of ptr.
• The two-dimensional array num will
be saved as a continuous block in the
memory.
• So, if increment the value of ptr by 1
it will move to the next block in the
allocated memory.
2D Arrays and Pointers
int arr1[3][5] = {{1,2,3,4,5},
{6,7,8,9,10},
{11,12,13,14,15}};

int (*p2)[5]; /* Declares p2 to be a pointer to an array of 5 integers */

p2 = arr1[0];

/* Giving only one dimension of ‘arr’ evaluates to the address of the first
row of array ‘arr’ */

printf("arr1[0][0]=%d\n",p2[0][0]);

printf("arr1[2][3]=%d\n",p2[2][3]);
Another way to declare 2D pointers
int arr1[3][5] = {{1,2,3,4,5},
{6,7,8,9,10},
{11,12,13,14,15}};

/* Declares p2 to be a pointer to a 2D array of 3 x 5 integers */

int (*p2)[3][5];
p2 = arr1; /* Or, p2 = &arr1[0][0] */
printf("arr1[0][0]=%d\n",(*p2)[0][0]);

printf("arr1[2][3]=%d\n",(*p2)[2][3]);

printf("arr1[1][4]=%d\n",(*p2)[1][4]);
Pointer Arithmetic in C

The C pointer arithmetic operations are slightly different from


the ones that we generally use for mathematical calculations.

These operations are:


⮚ Increment/Decrement of a Pointer
⮚ Addition of integer to a pointer
⮚ Subtraction of integer to a pointer
⮚ Subtracting two pointers of the same type
⮚ Comparison of pointers
Advantages of Pointers are :-

• Pointer provide direct access to the memory.


• Pointer provides a way to return more than one
value to the functions – Multiple parameters can
be declared as pointers through which values are
returned.
• Pointers provides an alternate way to access array
elements.
• Used to write system software and low level code –
Pointers are used to address devices in the system.
Disadvantages of Pointers are :-

• Pointer are slower than normal variables.


• Uninitialized pointer can cause segmentation fault
when it is dereferenced.
• If a pointer is accidentally assigned an address that
points to another variable in the program, it can lead
to corruption of data when we write using the
pointer.
• Basically, pointer bugs are difficult to handle. So, use
pointer effectively and correctly.

You might also like