SlideShare a Scribd company logo
1 of 47
UNIT I
POINTERS AND ARRAYS,
POINTERS AND STRINGS
P.ANANTHI, Assistant Professor, Kongu Engineering
College
1
TOPICS: POINTER
• Pointers : Introduction
• Pointer to pointer
• Null pointer, Generic Pointer and Dangling pointer
• Passing an array to a function
• Returning an array from function
• Array of pointers
• Pointers and 1D array
• Pointers and 2D array
• Using pointers for string manipulation
• Two-dimensional Array of strings
• Array of pointers to string
P.ANANTHI, Assistant Professor, Kongu Engineering College 2
MEMORY ACCESS
P.ANANTHI, Assistant Professor, Kongu Engineering
College
3
Memory access refers to the ability to read from or write to
specific locations in the computer's memory.
The memory in a computer is organized into a sequence of
bytes, each with a unique address.
MEMORY ACCESS
• Every variable is a memory location and every memory location has
its address defined which can be accessed through ampersand (&)
operator, which denotes an address in memory
P.ANANTHI, Assistant Professor, Kongu Engineering College 4
P.ANANTHI, Assistant Professor, Kongu Engineering
College
5
Address of a:
0x7ffd7218d764
Address of b:
0x7ffd7218d760
Address of c:
0x7ffd7218d75f
P.ANANTHI,
Assistant
Professor,
Kongu
Engineering
College
#include <stdio.h>
int main()
{
int a = 10;
double b = 20.5;
char c = 'A';
printf("Address of a: %pn", &a);
printf("Address of b: %pn", &b);
printf("Address of c: %pn", &c);
return 0;
}
6
Variables
• Variables in C are named storage locations that hold values of a
specific data type.
• When you declare a variable, the compiler allocates memory to
store its value, and you can access that memory using the
variable's name.
int age = 25;
// Declaring an integer variable 'age' and assigning it a value
7
P.ANANTHI, Assistant Professor, Kongu Engineering
College
Pointer
• Pointers are variables that store memory addresses. They allow
direct access to the memory location they point to.
• Pointers are declared with a specific data type, indicating the
type of data stored at the memory location.
• Example, int a=10;
• int *ptr; // Declaration of an integer pointer
10
10
a
Location
Value
Name of the variable
80F Address of the location
8
P.ANANTHI, Assistant Professor, Kongu Engineering
College
Pointer
• Value 10 can be accessed by using the variable name or the
address 80F
• Memory address are simply numbers can be assigned to some
other variable.
• The variable that holds the memory address is called pointer
variable
10
10
a
80F
10
80F
ptr
82C
Pointer name
Address of the
pointer
Address
of a
9
P.ANANTHI, Assistant Professor, Kongu Engineering
College
Pointer
• Value 10 can be accessed by using the variable name or the
address 80F
• Memory address are simply numbers can be assigned to some
other variable.
• The variable that holds the memory address is called pointer
variable
10
10
a
80F
10
80F
ptr
82C
Pointer name
Address of the
pointer
Address
of a
10
P.ANANTHI, Assistant Professor, Kongu Engineering
College
Address of operator
• The address-of operator (&) is used to get the memory address
of a variable.
int age = 25;
int *ptr = &age; // Assigning the address of 'age' to the pointer
'ptr'
11
P.ANANTHI, Assistant Professor, Kongu Engineering
College
Dereferencing operator
• The dereference operator (*) is used to access the value stored
at a memory address pointed to by a pointer.
int age = 25;
int *ptr = &age;
printf("Value at the memory address pointed by ptr: %dn", *ptr);
12
P.ANANTHI, Assistant Professor, Kongu Engineering
College
• Sample Program 1
• Pointer declaration and initialization
• Sample Program 2
• Pointer Basics
13
P.ANANTHI, Assistant Professor, Kongu Engineering
College
Pointer to Pointer (Double Pointer)
A pointer points to another
pointer
int pointer_name;
Double pointers are often used
for various purposes, such as
dynamic memory allocation,
passing pointers by reference,
and creating dynamic arrays of
pointers.
• Example
int *p;
int q;
int a=10;
p=&a;//Normal pointer
q=&p // Double pointer
printf("%d", q);
P.ANANTHI, Assistant Professor, Kongu Engineering
College
14
Pointer to Pointer (Double Pointer)
• Using pointers to point to other pointers
int x = 10;
int *ptr1 = &x;
int ptr2 = &ptr1;
printf("Value at the memory location pointed by ptr2: %dn",
ptr2);
15
P.ANANTHI, Assistant Professor, Kongu Engineering
College
Void or Generic pointer
• Pointer that is not associated with any data type.
• It can point to objects of any type but doesn't provide information about the type of data it
points to.
• Syntax: Void *pointer name
• A generic pointer can be compound to any pointer without using a cast and can be
assigned to NULL
• It very useful for designing functions that need to work with multiple datatype of its
arguments
16
P.ANANTHI, Assistant Professor, Kongu Engineering
College
Void or Generic pointer
• int x=10;
• void *ptr=&x;
• printf("%d", *(int *)ptr));
• *(int *) ptr=100;
• Void pointer sample Program
17
P.ANANTHI, Assistant Professor, Kongu Engineering
College
Null pointer
• A null pointer in C is a pointer that does not point to any memory location.
• It is a special constant value (often represented as 0 or NULL) that is assigned to a
pointer variable to indicate that it does not currently point to a valid memory address.
• Syntax:
• int *p=NULL;
• One main reason for using a NULL pointer is that many functions that returns a pointer
also needs to indicate an error condition when it occurs
• These functions can then return NULL to indicate failure
18
P.ANANTHI, Assistant Professor, Kongu Engineering
College
Null pointer
• A null pointer in C is a pointer that does not point to any memory
location.
• It is a special constant value (often represented as 0 or NULL)
that is assigned to a pointer variable to indicate that it does not
currently point to a valid memory address.
• Null pointer sample program
• Syntax:
• Int *p=NULL;
19
P.ANANTHI, Assistant Professor, Kongu Engineering
College
Dangling Pointer
• A dangling pointer in programming refers to a pointer that points
to a memory location that has been deallocated or freed.
• Accessing the value through such a pointer can lead to
undefined behavior and various issues, including crashes, data
corruption, or unpredictable program behavior.
• Dangling pointers often occur when the memory they point to is
released but the pointer is not updated or set to NULL
appropriately.
Dangling Pointer
#include <stdio.h>
int main() {
// Declare a variable 'x' on the stack
int x = 42;
// Declare a pointer 'ptr' and assign the address of 'x'
to it
int *ptr = &x;
// Access and print the value through the pointer
printf("Initial value through pointer: %dn", *ptr);
// Block scope for a new variable 'y'
{
int y = 99;
ptr = &y;
// Access and print the value through the pointer
printf("Value through pointer after reassignment:
%dn", *ptr);
}
// Attempt to access the value through the pointer
after 'y' has gone out of scope
// This may result in a dangling pointer
printf("Dangling pointer value: %dn", *ptr);
return 0;
Keep in mind
• The datatype of a pointer is different from the type of the variable it
points to
• The size of a pointer is generally fixed and does not depend on the
size of the object it points to
• A pointer can be assigned to 0
• An uninitialized or null pointer must not be dereferenced
• Adding 1 to a pointer variable doesn't necessarily add 1 to the value
stored by the pointer
• A pointer can snap its current link and points to another variable
22
P.ANANTHI, Assistant Professor, Kongu Engineering
College
Pointers and function
• Recalling Function!!!!
• A function is a statement that
represents a named body of program
code
• When it is invoked the code
associated with the function is
executed
• A function can accept one or more
values as arguments
• It reports the outcome of its action by
returning a value to the caller
#include <stdio.h>
// Function declaration
int addNumbers(int a, int b);
// Main function
int main() {
// Call the addNumbers function and store the result in a variable
int result = addNumbers(5, 7);
printf("Sum: %dn", result); // Print the result
return 0;
}
int addNumbers(int a, int b) { // Function definition for adding two numbers
return a + b;
}
Function pointer
• Function pointers in C allow you to store and call functions
through pointers. They provide a way to create more flexible
and dynamic code.
• Syntax:
• returnType (*pointerName)(parameterTypes);
• Function pointer
24
P.ANANTHI, Assistant Professor, Kongu Engineering
College
Pointers and Function
• When a function is called, the arguments in a function can be passed by value or passed by
reference.
• Callee/ Called is a function called by another and the caller is a function that calls another function
(the callee).
• The values that are passed in the function call are called the actual parameters.
• The values received by the function (when it is called ) are called the formal parameters.
int power( int f_base, f_exponent)
{…..........}
main()
Result = power(base, exponent)
Caller function
Called function
Formal parameters
Actual parameters
Pass by value
• Pass by value means that a copy of the actual parameter’s value is made
in memory, i.e. the caller and callee have two independent variables with
the same value. If the callee modifies the parameter value, the effect is
not visible to the caller.
void inccount(int count)
{ count= count +1; }
main()
{ count=0;
inccount(count);
print count; }
26
P.ANANTHI, Assistant Professor, Kongu Engineering
College
0
0+1
Changes in count are
locally made
Two copies of created in caller and called
points to different copies of the variable
"count"
The value of count is not updated after
the function call
#include <stdio.h>
void incrementByValue(int x) {
x++;
printf("Inside function: x = %dn", x);
}
int main() {
int num = 5;
printf("Before function call: num = %dn", num);
incrementByValue(num);
printf("After function call: num = %dn", num);
return 0;
}
27
P.ANANTHI, Assistant Professor, Kongu Engineering
College
Pass by reference
• Pass by reference (also called pass by address) means to pass the reference of an
argument in the calling function to the corresponding formal parameter of the called
function so that a copy of the address of the actual parameter is made in memory, i.e. the
caller and the callee use the same variable for the parameter. If the callee modifies the
parameter variable, the effect is visible to the caller’s variable.
void inccount(int &count)
{ count= count +1; }
main()
{ count=0;
inccount(count);
print count; }
1
Caller and called point to the same
variable " count". Variable count is
updated inside the function
The value of count is updated after the
function call
#include <stdio.h>
void incrementByReference(int *x) {
(*x)++;
printf("Inside function: *x = %dn", *x);
}
int main() {
int num = 5;
printf("Before function call: num = %dn", num);
incrementByReference(&num);
printf("After function call: num = %dn", num);
return 0;
}
29
P.ANANTHI, Assistant Professor, Kongu Engineering
College
Passing array to function using pointer
• A single array element or a entire array can be passed to a
function.
30
P.ANANTHI, Assistant Professor, Kongu Engineering
College
#include <stdio.h>
int main() {
// Declare an array
int numbers[] = {10, 20, 30, 40, 50};
// Declare a pointer and point it to the first element of the array
int *ptr = numbers;
// Accessing array elements using pointer
printf("First element: %dn", *ptr); // Output: 10
printf("Second element: %dn", *(ptr + 1)); // Output: 20
printf("Third element: %dn", *(ptr + 2)); // Output: 30
// You can also use array subscript notation with pointers
printf("Fourth element: %dn", ptr[3]); // Output: 40
return 0;
}
31
P.ANANTHI, Assistant Professor, Kongu Engineering
College
• Likewise, one dimensional and multi dimensional array can
be passed to a function as argument
One Dimension:
• While passing arrays to the argument, the name of the array is
passed as an argument
• 1 D ARRAY USING POINTER
32
P.ANANTHI, Assistant Professor, Kongu Engineering
College
• TWO DIMENSION
• To pass a 2D array to a function as an argument, starting
address of memory area reserved is passed as in 1D array
• 2D array to a function
33
P.ANANTHI, Assistant Professor, Kongu Engineering
College
Pointer
Arithmetic
• Incrementing or decrementing a
pointer to move to the next or
previous memory location.
int arr[] = {1, 2, 3, 4, 5};
int *ptr = arr; // Points to the first
element of the array
printf("First element: %dn", *ptr);
ptr++; // Move to the next element
printf("Second element: %dn", *ptr);
P.ANANTHI, Assistant Professor, Kongu Engineering
College
34
Array Access
with Pointers
• Using pointers to iterate
through an array.
int arr[] = {1, 2, 3, 4, 5};
int *ptr = arr;
for (int i = 0; i < 5; ++i) {
printf("%d ", *(ptr + i));
}
P.ANANTHI, Assistant Professor, Kongu Engineering
College
35
Pointer
Comparison
• Comparing two pointers to check their
relative positions in memory.
int arr[] = {1, 2, 3, 4, 5};
int *ptr1 = arr;
int *ptr2 = &arr[2];
if (ptr1 < ptr2) {
printf("ptr1 comes before ptr2 in
memory.n");
}
P.ANANTHI, Assistant Professor, Kongu Engineering
College
36
STRING Recall
A string is a sequence of zero or more characters enclosed within double quotes.
Strings are represented as array of characters. No separate data type is available in C
Example: "CSD"
String literals are enclosed with double quotes "CSD" where as characters literals are
enclosed in single quotes "C"
Quotes are not part of string but are delimiters
Every string constant is automatically terminated by the null character i.e '0' => ASCII
value is 0
37
P.Ananthi, Assistant Professor, Kongu Engineering
College
• The characters enclosed in double
quotes and terminating null character
are stored in continuous memory
location.
o EG: "RED CAR"
o The number of bytes required
includes null character also.
Memory required for string "RED
CAR" is 8
o The length of the string is
represented by the number of
characters present in the string 7.
P.Ananthi, Assistant Professor, Kongu Engineering College 38
R E D C A R '0'
Creating a
string
• In the following example we are creating a
string str using char character array of size 6.
• char str[6] = "Hello";
•
• The above string can be represented in memory as
follows.
• Each character in the string str takes 1 byte of memory
space.
Creating a pointer for the string
• The variable name of the
string str holds the address of the
first element of the array i.e., it points
at the starting memory address.
• So, we can 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.
• In the following code we are 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.
• In the following example
we are using while loop
to print the characters of
the string variable str.
• #include <stdio.h>
• int main(void) {
• // string variable
• char str[6] = "Hello";
•
• // pointer variable
• char *ptr = str;
•
• // print the string
• while(*ptr != '0') {
• printf("%c", *ptr);// move the ptr
pointer to the next memory location
• ptr++;
• }
• return 0;
• }
Using pointer to store string
int main() {
// pointer variable to store string
char *strPtr = "Hello";
// temporary pointer variable
char *t = strPtr;
// print the string
while(*t != '0') {
printf("%c", *t);
// move the t pointer to the next memory
location
t++;
}
We can achieve the same result by creating a character
pointer that points at a string value stored at some memory
location.
In the following example we are using character pointer
variable strPtr to store string value.
Array of strings
• We can create a two dimensional array and
save multiple strings in it.
• For example, in the given code we are
storing 4 cities name in a string array city.
• char city[4][12] = {
• "Chennai",
• "Kolkata",
• "Mumbai",
• "New Delhi"
• };
• The problem with this approach is that we
are allocating 4x12 = 48 bytes memory to
the city array and we are only using 33
bytes.
Pointers and String
• We can save those unused memory spaces by using pointers as shown below.
• char *cityPtr[4] = {
• "Chennai",
• "Kolkata",
• "Mumbai",
• "New Delhi"
• };
Summary
1. Introduction to Pointers:
- Pointers are variables that store memory addresses. They provide a way to directly manipulate
memory, enabling efficient and flexible programming.
2. Pointer to Pointer:
- A pointer that holds the address of another pointer. Useful in scenarios where multiple levels of
indirection are required.
3. Null Pointer, Generic Pointer, and Dangling Pointer:
- Discusses the concepts of null pointers (pointers with no valid address), generic pointers (void
pointers), and dangling pointers (pointers pointing to released memory).
4. Passing an Array to a Function:
- Explains how to pass arrays to functions, emphasizing the use of pointers to efficiently work with
arrays in functions.
5. Returning an Array from Function:
- Explores the technique of returning arrays from functions, often involving the use of pointers to
manage memory.
Summary
6. Array of Pointers:
- Describes the concept of an array where each element is a pointer, enabling the creation of dynamic data structures.
7. Pointers and 1D Array:
- Examines the relationship between pointers and one-dimensional arrays, highlighting how pointers can be used for array
manipulation.
8. Pointers and 2D Array:
- Discusses the use of pointers in managing two-dimensional arrays, which involves handling rows and columns efficiently.
9. Using Pointers for String Manipulation:
- Illustrates how pointers are employed for efficient manipulation of strings, emphasizing dynamic memory allocation for flexible
string handling.
10. Two-dimensional Array of Strings:
- Explores the combination of pointers and arrays to handle two-dimensional arrays of strings.
11. Array of Pointers to String:
- Focuses on the concept of an array where each element is a pointer to a string, allowing for dynamic string management.
Pointers and Array, pointer and String.pptx

More Related Content

What's hot (20)

Pointers in c - Mohammad Salman
Pointers in c - Mohammad SalmanPointers in c - Mohammad Salman
Pointers in c - Mohammad Salman
 
Pointers in C
Pointers in CPointers in C
Pointers in C
 
C programming - Pointers
C programming - PointersC programming - Pointers
C programming - Pointers
 
Storage classes in C
Storage classes in CStorage classes in C
Storage classes in C
 
Union in C programming
Union in C programmingUnion in C programming
Union in C programming
 
Pointers in c v5 12102017 1
Pointers in c v5 12102017 1Pointers in c v5 12102017 1
Pointers in c v5 12102017 1
 
Architecture of 8085
Architecture of 8085Architecture of 8085
Architecture of 8085
 
Storage classes in C
Storage classes in C Storage classes in C
Storage classes in C
 
Pointers C programming
Pointers  C programmingPointers  C programming
Pointers C programming
 
File Handling in Python
File Handling in PythonFile Handling in Python
File Handling in Python
 
Storage class in c
Storage class in cStorage class in c
Storage class in c
 
Type conversion
Type conversionType conversion
Type conversion
 
INTERNAL STRUCTURE OF 8086 MICROPROCESSOR
INTERNAL STRUCTURE OF  8086 MICROPROCESSORINTERNAL STRUCTURE OF  8086 MICROPROCESSOR
INTERNAL STRUCTURE OF 8086 MICROPROCESSOR
 
File in C Programming
File in C ProgrammingFile in C Programming
File in C Programming
 
C formatted and unformatted input and output constructs
C  formatted and unformatted input and output constructsC  formatted and unformatted input and output constructs
C formatted and unformatted input and output constructs
 
Function in C
Function in CFunction in C
Function in C
 
8051 microcontroller features
8051 microcontroller features8051 microcontroller features
8051 microcontroller features
 
File in C language
File in C languageFile in C language
File in C language
 
Lil endian.ppt
Lil endian.pptLil endian.ppt
Lil endian.ppt
 
Pointers
PointersPointers
Pointers
 

Similar to Pointers and Array, pointer and String.pptx

FYBSC(CS)_UNIT-1_Pointers in C.pptx
FYBSC(CS)_UNIT-1_Pointers in C.pptxFYBSC(CS)_UNIT-1_Pointers in C.pptx
FYBSC(CS)_UNIT-1_Pointers in C.pptxsangeeta borde
 
Chp3(pointers ref)
Chp3(pointers ref)Chp3(pointers ref)
Chp3(pointers ref)Mohd Effandi
 
358 33 powerpoint-slides_3-pointers_chapter-3
358 33 powerpoint-slides_3-pointers_chapter-3358 33 powerpoint-slides_3-pointers_chapter-3
358 33 powerpoint-slides_3-pointers_chapter-3sumitbardhan
 
btech-1picu-5pointerstructureunionandintrotofilehandling-150122010700-conver.ppt
btech-1picu-5pointerstructureunionandintrotofilehandling-150122010700-conver.pptbtech-1picu-5pointerstructureunionandintrotofilehandling-150122010700-conver.ppt
btech-1picu-5pointerstructureunionandintrotofilehandling-150122010700-conver.pptchintuyadav19
 
Diploma ii cfpc- u-5.1 pointer, structure ,union and intro to file handling
Diploma ii  cfpc- u-5.1 pointer, structure ,union and intro to file handlingDiploma ii  cfpc- u-5.1 pointer, structure ,union and intro to file handling
Diploma ii cfpc- u-5.1 pointer, structure ,union and intro to file handlingRai University
 
pointer, structure ,union and intro to file handling
pointer, structure ,union and intro to file handlingpointer, structure ,union and intro to file handling
pointer, structure ,union and intro to file handlingRai University
 
Mca 1 pic u-5 pointer, structure ,union and intro to file handling
Mca 1 pic u-5 pointer, structure ,union and intro to file handlingMca 1 pic u-5 pointer, structure ,union and intro to file handling
Mca 1 pic u-5 pointer, structure ,union and intro to file handlingRai University
 
Btech 1 pic u-5 pointer, structure ,union and intro to file handling
Btech 1 pic u-5 pointer, structure ,union and intro to file handlingBtech 1 pic u-5 pointer, structure ,union and intro to file handling
Btech 1 pic u-5 pointer, structure ,union and intro to file handlingRai University
 
pointer, structure ,union and intro to file handling
pointer, structure ,union and intro to file handlingpointer, structure ,union and intro to file handling
pointer, structure ,union and intro to file handlingRai University
 
Bsc cs 1 pic u-5 pointer, structure ,union and intro to file handling
Bsc cs 1 pic u-5 pointer, structure ,union and intro to file handlingBsc cs 1 pic u-5 pointer, structure ,union and intro to file handling
Bsc cs 1 pic u-5 pointer, structure ,union and intro to file handlingRai University
 
Lap trinh C co ban va nang cao
Lap trinh C co ban va nang caoLap trinh C co ban va nang cao
Lap trinh C co ban va nang caoVietJackTeam
 

Similar to Pointers and Array, pointer and String.pptx (20)

Pointers in C Programming
Pointers in C ProgrammingPointers in C Programming
Pointers in C Programming
 
FYBSC(CS)_UNIT-1_Pointers in C.pptx
FYBSC(CS)_UNIT-1_Pointers in C.pptxFYBSC(CS)_UNIT-1_Pointers in C.pptx
FYBSC(CS)_UNIT-1_Pointers in C.pptx
 
Chp3(pointers ref)
Chp3(pointers ref)Chp3(pointers ref)
Chp3(pointers ref)
 
358 33 powerpoint-slides_3-pointers_chapter-3
358 33 powerpoint-slides_3-pointers_chapter-3358 33 powerpoint-slides_3-pointers_chapter-3
358 33 powerpoint-slides_3-pointers_chapter-3
 
btech-1picu-5pointerstructureunionandintrotofilehandling-150122010700-conver.ppt
btech-1picu-5pointerstructureunionandintrotofilehandling-150122010700-conver.pptbtech-1picu-5pointerstructureunionandintrotofilehandling-150122010700-conver.ppt
btech-1picu-5pointerstructureunionandintrotofilehandling-150122010700-conver.ppt
 
Diploma ii cfpc- u-5.1 pointer, structure ,union and intro to file handling
Diploma ii  cfpc- u-5.1 pointer, structure ,union and intro to file handlingDiploma ii  cfpc- u-5.1 pointer, structure ,union and intro to file handling
Diploma ii cfpc- u-5.1 pointer, structure ,union and intro to file handling
 
pointer, structure ,union and intro to file handling
pointer, structure ,union and intro to file handlingpointer, structure ,union and intro to file handling
pointer, structure ,union and intro to file handling
 
Mca 1 pic u-5 pointer, structure ,union and intro to file handling
Mca 1 pic u-5 pointer, structure ,union and intro to file handlingMca 1 pic u-5 pointer, structure ,union and intro to file handling
Mca 1 pic u-5 pointer, structure ,union and intro to file handling
 
Btech 1 pic u-5 pointer, structure ,union and intro to file handling
Btech 1 pic u-5 pointer, structure ,union and intro to file handlingBtech 1 pic u-5 pointer, structure ,union and intro to file handling
Btech 1 pic u-5 pointer, structure ,union and intro to file handling
 
pointer, structure ,union and intro to file handling
pointer, structure ,union and intro to file handlingpointer, structure ,union and intro to file handling
pointer, structure ,union and intro to file handling
 
Bsc cs 1 pic u-5 pointer, structure ,union and intro to file handling
Bsc cs 1 pic u-5 pointer, structure ,union and intro to file handlingBsc cs 1 pic u-5 pointer, structure ,union and intro to file handling
Bsc cs 1 pic u-5 pointer, structure ,union and intro to file handling
 
4 Pointers.pptx
4 Pointers.pptx4 Pointers.pptx
4 Pointers.pptx
 
Advanced pointers
Advanced pointersAdvanced pointers
Advanced pointers
 
Pointer.pptx
Pointer.pptxPointer.pptx
Pointer.pptx
 
pointers (1).ppt
pointers (1).pptpointers (1).ppt
pointers (1).ppt
 
C pointer basics
C pointer basicsC pointer basics
C pointer basics
 
PSPC--UNIT-5.pdf
PSPC--UNIT-5.pdfPSPC--UNIT-5.pdf
PSPC--UNIT-5.pdf
 
Session 5
Session 5Session 5
Session 5
 
COM1407: Working with Pointers
COM1407: Working with PointersCOM1407: Working with Pointers
COM1407: Working with Pointers
 
Lap trinh C co ban va nang cao
Lap trinh C co ban va nang caoLap trinh C co ban va nang cao
Lap trinh C co ban va nang cao
 

Recently uploaded

College Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service NashikCollege Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service NashikCall Girls in Nagpur High Profile
 
247267395-1-Symmetric-and-distributed-shared-memory-architectures-ppt (1).ppt
247267395-1-Symmetric-and-distributed-shared-memory-architectures-ppt (1).ppt247267395-1-Symmetric-and-distributed-shared-memory-architectures-ppt (1).ppt
247267395-1-Symmetric-and-distributed-shared-memory-architectures-ppt (1).pptssuser5c9d4b1
 
Introduction and different types of Ethernet.pptx
Introduction and different types of Ethernet.pptxIntroduction and different types of Ethernet.pptx
Introduction and different types of Ethernet.pptxupamatechverse
 
Software Development Life Cycle By Team Orange (Dept. of Pharmacy)
Software Development Life Cycle By  Team Orange (Dept. of Pharmacy)Software Development Life Cycle By  Team Orange (Dept. of Pharmacy)
Software Development Life Cycle By Team Orange (Dept. of Pharmacy)Suman Mia
 
Top Rated Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...
Top Rated  Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...Top Rated  Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...
Top Rated Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...Call Girls in Nagpur High Profile
 
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptxDecoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptxJoão Esperancinha
 
Processing & Properties of Floor and Wall Tiles.pptx
Processing & Properties of Floor and Wall Tiles.pptxProcessing & Properties of Floor and Wall Tiles.pptx
Processing & Properties of Floor and Wall Tiles.pptxpranjaldaimarysona
 
Call Girls Service Nashik Vaishnavi 7001305949 Independent Escort Service Nashik
Call Girls Service Nashik Vaishnavi 7001305949 Independent Escort Service NashikCall Girls Service Nashik Vaishnavi 7001305949 Independent Escort Service Nashik
Call Girls Service Nashik Vaishnavi 7001305949 Independent Escort Service NashikCall Girls in Nagpur High Profile
 
(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...
(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...
(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...ranjana rawat
 
Porous Ceramics seminar and technical writing
Porous Ceramics seminar and technical writingPorous Ceramics seminar and technical writing
Porous Ceramics seminar and technical writingrakeshbaidya232001
 
Microscopic Analysis of Ceramic Materials.pptx
Microscopic Analysis of Ceramic Materials.pptxMicroscopic Analysis of Ceramic Materials.pptx
Microscopic Analysis of Ceramic Materials.pptxpurnimasatapathy1234
 
(TARA) Talegaon Dabhade Call Girls Just Call 7001035870 [ Cash on Delivery ] ...
(TARA) Talegaon Dabhade Call Girls Just Call 7001035870 [ Cash on Delivery ] ...(TARA) Talegaon Dabhade Call Girls Just Call 7001035870 [ Cash on Delivery ] ...
(TARA) Talegaon Dabhade Call Girls Just Call 7001035870 [ Cash on Delivery ] ...ranjana rawat
 
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur Escorts
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur EscortsCall Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur Escorts
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur High Profile
 
the ladakh protest in leh ladakh 2024 sonam wangchuk.pptx
the ladakh protest in leh ladakh 2024 sonam wangchuk.pptxthe ladakh protest in leh ladakh 2024 sonam wangchuk.pptx
the ladakh protest in leh ladakh 2024 sonam wangchuk.pptxhumanexperienceaaa
 
UNIT-III FMM. DIMENSIONAL ANALYSIS
UNIT-III FMM.        DIMENSIONAL ANALYSISUNIT-III FMM.        DIMENSIONAL ANALYSIS
UNIT-III FMM. DIMENSIONAL ANALYSISrknatarajan
 
Coefficient of Thermal Expansion and their Importance.pptx
Coefficient of Thermal Expansion and their Importance.pptxCoefficient of Thermal Expansion and their Importance.pptx
Coefficient of Thermal Expansion and their Importance.pptxAsutosh Ranjan
 
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...ranjana rawat
 
Booking open Available Pune Call Girls Koregaon Park 6297143586 Call Hot Ind...
Booking open Available Pune Call Girls Koregaon Park  6297143586 Call Hot Ind...Booking open Available Pune Call Girls Koregaon Park  6297143586 Call Hot Ind...
Booking open Available Pune Call Girls Koregaon Park 6297143586 Call Hot Ind...Call Girls in Nagpur High Profile
 

Recently uploaded (20)

College Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service NashikCollege Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
 
247267395-1-Symmetric-and-distributed-shared-memory-architectures-ppt (1).ppt
247267395-1-Symmetric-and-distributed-shared-memory-architectures-ppt (1).ppt247267395-1-Symmetric-and-distributed-shared-memory-architectures-ppt (1).ppt
247267395-1-Symmetric-and-distributed-shared-memory-architectures-ppt (1).ppt
 
Introduction and different types of Ethernet.pptx
Introduction and different types of Ethernet.pptxIntroduction and different types of Ethernet.pptx
Introduction and different types of Ethernet.pptx
 
Software Development Life Cycle By Team Orange (Dept. of Pharmacy)
Software Development Life Cycle By  Team Orange (Dept. of Pharmacy)Software Development Life Cycle By  Team Orange (Dept. of Pharmacy)
Software Development Life Cycle By Team Orange (Dept. of Pharmacy)
 
DJARUM4D - SLOT GACOR ONLINE | SLOT DEMO ONLINE
DJARUM4D - SLOT GACOR ONLINE | SLOT DEMO ONLINEDJARUM4D - SLOT GACOR ONLINE | SLOT DEMO ONLINE
DJARUM4D - SLOT GACOR ONLINE | SLOT DEMO ONLINE
 
Call Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCR
Call Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCRCall Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCR
Call Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCR
 
Top Rated Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...
Top Rated  Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...Top Rated  Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...
Top Rated Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...
 
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptxDecoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
 
Processing & Properties of Floor and Wall Tiles.pptx
Processing & Properties of Floor and Wall Tiles.pptxProcessing & Properties of Floor and Wall Tiles.pptx
Processing & Properties of Floor and Wall Tiles.pptx
 
Call Girls Service Nashik Vaishnavi 7001305949 Independent Escort Service Nashik
Call Girls Service Nashik Vaishnavi 7001305949 Independent Escort Service NashikCall Girls Service Nashik Vaishnavi 7001305949 Independent Escort Service Nashik
Call Girls Service Nashik Vaishnavi 7001305949 Independent Escort Service Nashik
 
(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...
(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...
(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...
 
Porous Ceramics seminar and technical writing
Porous Ceramics seminar and technical writingPorous Ceramics seminar and technical writing
Porous Ceramics seminar and technical writing
 
Microscopic Analysis of Ceramic Materials.pptx
Microscopic Analysis of Ceramic Materials.pptxMicroscopic Analysis of Ceramic Materials.pptx
Microscopic Analysis of Ceramic Materials.pptx
 
(TARA) Talegaon Dabhade Call Girls Just Call 7001035870 [ Cash on Delivery ] ...
(TARA) Talegaon Dabhade Call Girls Just Call 7001035870 [ Cash on Delivery ] ...(TARA) Talegaon Dabhade Call Girls Just Call 7001035870 [ Cash on Delivery ] ...
(TARA) Talegaon Dabhade Call Girls Just Call 7001035870 [ Cash on Delivery ] ...
 
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur Escorts
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur EscortsCall Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur Escorts
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur Escorts
 
the ladakh protest in leh ladakh 2024 sonam wangchuk.pptx
the ladakh protest in leh ladakh 2024 sonam wangchuk.pptxthe ladakh protest in leh ladakh 2024 sonam wangchuk.pptx
the ladakh protest in leh ladakh 2024 sonam wangchuk.pptx
 
UNIT-III FMM. DIMENSIONAL ANALYSIS
UNIT-III FMM.        DIMENSIONAL ANALYSISUNIT-III FMM.        DIMENSIONAL ANALYSIS
UNIT-III FMM. DIMENSIONAL ANALYSIS
 
Coefficient of Thermal Expansion and their Importance.pptx
Coefficient of Thermal Expansion and their Importance.pptxCoefficient of Thermal Expansion and their Importance.pptx
Coefficient of Thermal Expansion and their Importance.pptx
 
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
 
Booking open Available Pune Call Girls Koregaon Park 6297143586 Call Hot Ind...
Booking open Available Pune Call Girls Koregaon Park  6297143586 Call Hot Ind...Booking open Available Pune Call Girls Koregaon Park  6297143586 Call Hot Ind...
Booking open Available Pune Call Girls Koregaon Park 6297143586 Call Hot Ind...
 

Pointers and Array, pointer and String.pptx

  • 1. UNIT I POINTERS AND ARRAYS, POINTERS AND STRINGS P.ANANTHI, Assistant Professor, Kongu Engineering College 1
  • 2. TOPICS: POINTER • Pointers : Introduction • Pointer to pointer • Null pointer, Generic Pointer and Dangling pointer • Passing an array to a function • Returning an array from function • Array of pointers • Pointers and 1D array • Pointers and 2D array • Using pointers for string manipulation • Two-dimensional Array of strings • Array of pointers to string P.ANANTHI, Assistant Professor, Kongu Engineering College 2
  • 3. MEMORY ACCESS P.ANANTHI, Assistant Professor, Kongu Engineering College 3 Memory access refers to the ability to read from or write to specific locations in the computer's memory. The memory in a computer is organized into a sequence of bytes, each with a unique address.
  • 4. MEMORY ACCESS • Every variable is a memory location and every memory location has its address defined which can be accessed through ampersand (&) operator, which denotes an address in memory P.ANANTHI, Assistant Professor, Kongu Engineering College 4
  • 5. P.ANANTHI, Assistant Professor, Kongu Engineering College 5
  • 6. Address of a: 0x7ffd7218d764 Address of b: 0x7ffd7218d760 Address of c: 0x7ffd7218d75f P.ANANTHI, Assistant Professor, Kongu Engineering College #include <stdio.h> int main() { int a = 10; double b = 20.5; char c = 'A'; printf("Address of a: %pn", &a); printf("Address of b: %pn", &b); printf("Address of c: %pn", &c); return 0; } 6
  • 7. Variables • Variables in C are named storage locations that hold values of a specific data type. • When you declare a variable, the compiler allocates memory to store its value, and you can access that memory using the variable's name. int age = 25; // Declaring an integer variable 'age' and assigning it a value 7 P.ANANTHI, Assistant Professor, Kongu Engineering College
  • 8. Pointer • Pointers are variables that store memory addresses. They allow direct access to the memory location they point to. • Pointers are declared with a specific data type, indicating the type of data stored at the memory location. • Example, int a=10; • int *ptr; // Declaration of an integer pointer 10 10 a Location Value Name of the variable 80F Address of the location 8 P.ANANTHI, Assistant Professor, Kongu Engineering College
  • 9. Pointer • Value 10 can be accessed by using the variable name or the address 80F • Memory address are simply numbers can be assigned to some other variable. • The variable that holds the memory address is called pointer variable 10 10 a 80F 10 80F ptr 82C Pointer name Address of the pointer Address of a 9 P.ANANTHI, Assistant Professor, Kongu Engineering College
  • 10. Pointer • Value 10 can be accessed by using the variable name or the address 80F • Memory address are simply numbers can be assigned to some other variable. • The variable that holds the memory address is called pointer variable 10 10 a 80F 10 80F ptr 82C Pointer name Address of the pointer Address of a 10 P.ANANTHI, Assistant Professor, Kongu Engineering College
  • 11. Address of operator • The address-of operator (&) is used to get the memory address of a variable. int age = 25; int *ptr = &age; // Assigning the address of 'age' to the pointer 'ptr' 11 P.ANANTHI, Assistant Professor, Kongu Engineering College
  • 12. Dereferencing operator • The dereference operator (*) is used to access the value stored at a memory address pointed to by a pointer. int age = 25; int *ptr = &age; printf("Value at the memory address pointed by ptr: %dn", *ptr); 12 P.ANANTHI, Assistant Professor, Kongu Engineering College
  • 13. • Sample Program 1 • Pointer declaration and initialization • Sample Program 2 • Pointer Basics 13 P.ANANTHI, Assistant Professor, Kongu Engineering College
  • 14. Pointer to Pointer (Double Pointer) A pointer points to another pointer int pointer_name; Double pointers are often used for various purposes, such as dynamic memory allocation, passing pointers by reference, and creating dynamic arrays of pointers. • Example int *p; int q; int a=10; p=&a;//Normal pointer q=&p // Double pointer printf("%d", q); P.ANANTHI, Assistant Professor, Kongu Engineering College 14
  • 15. Pointer to Pointer (Double Pointer) • Using pointers to point to other pointers int x = 10; int *ptr1 = &x; int ptr2 = &ptr1; printf("Value at the memory location pointed by ptr2: %dn", ptr2); 15 P.ANANTHI, Assistant Professor, Kongu Engineering College
  • 16. Void or Generic pointer • Pointer that is not associated with any data type. • It can point to objects of any type but doesn't provide information about the type of data it points to. • Syntax: Void *pointer name • A generic pointer can be compound to any pointer without using a cast and can be assigned to NULL • It very useful for designing functions that need to work with multiple datatype of its arguments 16 P.ANANTHI, Assistant Professor, Kongu Engineering College
  • 17. Void or Generic pointer • int x=10; • void *ptr=&x; • printf("%d", *(int *)ptr)); • *(int *) ptr=100; • Void pointer sample Program 17 P.ANANTHI, Assistant Professor, Kongu Engineering College
  • 18. Null pointer • A null pointer in C is a pointer that does not point to any memory location. • It is a special constant value (often represented as 0 or NULL) that is assigned to a pointer variable to indicate that it does not currently point to a valid memory address. • Syntax: • int *p=NULL; • One main reason for using a NULL pointer is that many functions that returns a pointer also needs to indicate an error condition when it occurs • These functions can then return NULL to indicate failure 18 P.ANANTHI, Assistant Professor, Kongu Engineering College
  • 19. Null pointer • A null pointer in C is a pointer that does not point to any memory location. • It is a special constant value (often represented as 0 or NULL) that is assigned to a pointer variable to indicate that it does not currently point to a valid memory address. • Null pointer sample program • Syntax: • Int *p=NULL; 19 P.ANANTHI, Assistant Professor, Kongu Engineering College
  • 20. Dangling Pointer • A dangling pointer in programming refers to a pointer that points to a memory location that has been deallocated or freed. • Accessing the value through such a pointer can lead to undefined behavior and various issues, including crashes, data corruption, or unpredictable program behavior. • Dangling pointers often occur when the memory they point to is released but the pointer is not updated or set to NULL appropriately.
  • 21. Dangling Pointer #include <stdio.h> int main() { // Declare a variable 'x' on the stack int x = 42; // Declare a pointer 'ptr' and assign the address of 'x' to it int *ptr = &x; // Access and print the value through the pointer printf("Initial value through pointer: %dn", *ptr); // Block scope for a new variable 'y' { int y = 99; ptr = &y; // Access and print the value through the pointer printf("Value through pointer after reassignment: %dn", *ptr); } // Attempt to access the value through the pointer after 'y' has gone out of scope // This may result in a dangling pointer printf("Dangling pointer value: %dn", *ptr); return 0;
  • 22. Keep in mind • The datatype of a pointer is different from the type of the variable it points to • The size of a pointer is generally fixed and does not depend on the size of the object it points to • A pointer can be assigned to 0 • An uninitialized or null pointer must not be dereferenced • Adding 1 to a pointer variable doesn't necessarily add 1 to the value stored by the pointer • A pointer can snap its current link and points to another variable 22 P.ANANTHI, Assistant Professor, Kongu Engineering College
  • 23. Pointers and function • Recalling Function!!!! • A function is a statement that represents a named body of program code • When it is invoked the code associated with the function is executed • A function can accept one or more values as arguments • It reports the outcome of its action by returning a value to the caller #include <stdio.h> // Function declaration int addNumbers(int a, int b); // Main function int main() { // Call the addNumbers function and store the result in a variable int result = addNumbers(5, 7); printf("Sum: %dn", result); // Print the result return 0; } int addNumbers(int a, int b) { // Function definition for adding two numbers return a + b; }
  • 24. Function pointer • Function pointers in C allow you to store and call functions through pointers. They provide a way to create more flexible and dynamic code. • Syntax: • returnType (*pointerName)(parameterTypes); • Function pointer 24 P.ANANTHI, Assistant Professor, Kongu Engineering College
  • 25. Pointers and Function • When a function is called, the arguments in a function can be passed by value or passed by reference. • Callee/ Called is a function called by another and the caller is a function that calls another function (the callee). • The values that are passed in the function call are called the actual parameters. • The values received by the function (when it is called ) are called the formal parameters. int power( int f_base, f_exponent) {…..........} main() Result = power(base, exponent) Caller function Called function Formal parameters Actual parameters
  • 26. Pass by value • Pass by value means that a copy of the actual parameter’s value is made in memory, i.e. the caller and callee have two independent variables with the same value. If the callee modifies the parameter value, the effect is not visible to the caller. void inccount(int count) { count= count +1; } main() { count=0; inccount(count); print count; } 26 P.ANANTHI, Assistant Professor, Kongu Engineering College 0 0+1 Changes in count are locally made Two copies of created in caller and called points to different copies of the variable "count" The value of count is not updated after the function call
  • 27. #include <stdio.h> void incrementByValue(int x) { x++; printf("Inside function: x = %dn", x); } int main() { int num = 5; printf("Before function call: num = %dn", num); incrementByValue(num); printf("After function call: num = %dn", num); return 0; } 27 P.ANANTHI, Assistant Professor, Kongu Engineering College
  • 28. Pass by reference • Pass by reference (also called pass by address) means to pass the reference of an argument in the calling function to the corresponding formal parameter of the called function so that a copy of the address of the actual parameter is made in memory, i.e. the caller and the callee use the same variable for the parameter. If the callee modifies the parameter variable, the effect is visible to the caller’s variable. void inccount(int &count) { count= count +1; } main() { count=0; inccount(count); print count; } 1 Caller and called point to the same variable " count". Variable count is updated inside the function The value of count is updated after the function call
  • 29. #include <stdio.h> void incrementByReference(int *x) { (*x)++; printf("Inside function: *x = %dn", *x); } int main() { int num = 5; printf("Before function call: num = %dn", num); incrementByReference(&num); printf("After function call: num = %dn", num); return 0; } 29 P.ANANTHI, Assistant Professor, Kongu Engineering College
  • 30. Passing array to function using pointer • A single array element or a entire array can be passed to a function. 30 P.ANANTHI, Assistant Professor, Kongu Engineering College
  • 31. #include <stdio.h> int main() { // Declare an array int numbers[] = {10, 20, 30, 40, 50}; // Declare a pointer and point it to the first element of the array int *ptr = numbers; // Accessing array elements using pointer printf("First element: %dn", *ptr); // Output: 10 printf("Second element: %dn", *(ptr + 1)); // Output: 20 printf("Third element: %dn", *(ptr + 2)); // Output: 30 // You can also use array subscript notation with pointers printf("Fourth element: %dn", ptr[3]); // Output: 40 return 0; } 31 P.ANANTHI, Assistant Professor, Kongu Engineering College
  • 32. • Likewise, one dimensional and multi dimensional array can be passed to a function as argument One Dimension: • While passing arrays to the argument, the name of the array is passed as an argument • 1 D ARRAY USING POINTER 32 P.ANANTHI, Assistant Professor, Kongu Engineering College
  • 33. • TWO DIMENSION • To pass a 2D array to a function as an argument, starting address of memory area reserved is passed as in 1D array • 2D array to a function 33 P.ANANTHI, Assistant Professor, Kongu Engineering College
  • 34. Pointer Arithmetic • Incrementing or decrementing a pointer to move to the next or previous memory location. int arr[] = {1, 2, 3, 4, 5}; int *ptr = arr; // Points to the first element of the array printf("First element: %dn", *ptr); ptr++; // Move to the next element printf("Second element: %dn", *ptr); P.ANANTHI, Assistant Professor, Kongu Engineering College 34
  • 35. Array Access with Pointers • Using pointers to iterate through an array. int arr[] = {1, 2, 3, 4, 5}; int *ptr = arr; for (int i = 0; i < 5; ++i) { printf("%d ", *(ptr + i)); } P.ANANTHI, Assistant Professor, Kongu Engineering College 35
  • 36. Pointer Comparison • Comparing two pointers to check their relative positions in memory. int arr[] = {1, 2, 3, 4, 5}; int *ptr1 = arr; int *ptr2 = &arr[2]; if (ptr1 < ptr2) { printf("ptr1 comes before ptr2 in memory.n"); } P.ANANTHI, Assistant Professor, Kongu Engineering College 36
  • 37. STRING Recall A string is a sequence of zero or more characters enclosed within double quotes. Strings are represented as array of characters. No separate data type is available in C Example: "CSD" String literals are enclosed with double quotes "CSD" where as characters literals are enclosed in single quotes "C" Quotes are not part of string but are delimiters Every string constant is automatically terminated by the null character i.e '0' => ASCII value is 0 37 P.Ananthi, Assistant Professor, Kongu Engineering College
  • 38. • The characters enclosed in double quotes and terminating null character are stored in continuous memory location. o EG: "RED CAR" o The number of bytes required includes null character also. Memory required for string "RED CAR" is 8 o The length of the string is represented by the number of characters present in the string 7. P.Ananthi, Assistant Professor, Kongu Engineering College 38 R E D C A R '0'
  • 39. Creating a string • In the following example we are creating a string str using char character array of size 6. • char str[6] = "Hello"; • • The above string can be represented in memory as follows. • Each character in the string str takes 1 byte of memory space.
  • 40. Creating a pointer for the string • The variable name of the string str holds the address of the first element of the array i.e., it points at the starting memory address. • So, we can 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. • In the following code we are assigning the address of the string str to the pointer ptr. • char *ptr = str;
  • 41. 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. • In the following example we are using while loop to print the characters of the string variable str. • #include <stdio.h> • int main(void) { • // string variable • char str[6] = "Hello"; • • // pointer variable • char *ptr = str; • • // print the string • while(*ptr != '0') { • printf("%c", *ptr);// move the ptr pointer to the next memory location • ptr++; • } • return 0; • }
  • 42. Using pointer to store string int main() { // pointer variable to store string char *strPtr = "Hello"; // temporary pointer variable char *t = strPtr; // print the string while(*t != '0') { printf("%c", *t); // move the t pointer to the next memory location t++; } We can achieve the same result by creating a character pointer that points at a string value stored at some memory location. In the following example we are using character pointer variable strPtr to store string value.
  • 43. Array of strings • We can create a two dimensional array and save multiple strings in it. • For example, in the given code we are storing 4 cities name in a string array city. • char city[4][12] = { • "Chennai", • "Kolkata", • "Mumbai", • "New Delhi" • }; • The problem with this approach is that we are allocating 4x12 = 48 bytes memory to the city array and we are only using 33 bytes.
  • 44. Pointers and String • We can save those unused memory spaces by using pointers as shown below. • char *cityPtr[4] = { • "Chennai", • "Kolkata", • "Mumbai", • "New Delhi" • };
  • 45. Summary 1. Introduction to Pointers: - Pointers are variables that store memory addresses. They provide a way to directly manipulate memory, enabling efficient and flexible programming. 2. Pointer to Pointer: - A pointer that holds the address of another pointer. Useful in scenarios where multiple levels of indirection are required. 3. Null Pointer, Generic Pointer, and Dangling Pointer: - Discusses the concepts of null pointers (pointers with no valid address), generic pointers (void pointers), and dangling pointers (pointers pointing to released memory). 4. Passing an Array to a Function: - Explains how to pass arrays to functions, emphasizing the use of pointers to efficiently work with arrays in functions. 5. Returning an Array from Function: - Explores the technique of returning arrays from functions, often involving the use of pointers to manage memory.
  • 46. Summary 6. Array of Pointers: - Describes the concept of an array where each element is a pointer, enabling the creation of dynamic data structures. 7. Pointers and 1D Array: - Examines the relationship between pointers and one-dimensional arrays, highlighting how pointers can be used for array manipulation. 8. Pointers and 2D Array: - Discusses the use of pointers in managing two-dimensional arrays, which involves handling rows and columns efficiently. 9. Using Pointers for String Manipulation: - Illustrates how pointers are employed for efficient manipulation of strings, emphasizing dynamic memory allocation for flexible string handling. 10. Two-dimensional Array of Strings: - Explores the combination of pointers and arrays to handle two-dimensional arrays of strings. 11. Array of Pointers to String: - Focuses on the concept of an array where each element is a pointer to a string, allowing for dynamic string management.