SlideShare uma empresa Scribd logo
1 de 6
Baixar para ler offline
An Introduction to Pointers Intro to Programming
MUHAMMAD HAMMAD WASEEM 1
An Introduction to Pointers
Which feature of C do beginners find most difficult to understand? The answer is easy: pointers.
The difficulty beginners have with pointers has much to do with C’s pointer terminology than the
actual concept. In our discussion of C pointers, therefore, we will try to avoid this difficulty by
explaining pointers in terms of programming concepts we already understand.
The first thing we want to do is explain the rationale of C’s pointer notation. Consider the
declaration, int i = 3 ;
This declaration tells the C compiler to:
a) Reserve space in memory to hold the integer value.
b) Associate the name i with this memory location.
c) Store the value 3 at this location.
We may represent i’s location in memory by the following memory map.
We see that the computer has selected memory location 65524 as the place to store the value 3.
The location number 65524 is not a number to be relied upon, because some other time the computer
may choose a different location for storing the value 3. The important point is, i’s address in memory is
a number.
We can print this address number through the following program:
main( )
{
int i = 3 ;
printf ( "nAddress of i = %u", &i ) ;
printf ( "nValue of i = %d", i ) ;
}
The output of the above program would be:
Address of i = 65524
Value of i = 3
Look at the first printf( ) statement carefully. ‘&’ used in this statement is C’s ‘address of’
operator. The expression &i returns the address of the variable i, which in this case happens to be
65524.
The other pointer operator available in C is ‘*’, called ‘value at address’ operator. It gives the value
stored at a particular address. The ‘value at address’ operator is also called ‘indirection’ operator.
Observe carefully the output of the following program:
main( )
{
int i = 3 ;
printf ( "nAddress of i = %u", &i ) ;
printf ( "nValue of i = %d", i ) ;
An Introduction to Pointers Intro to Programming
MUHAMMAD HAMMAD WASEEM 2
printf ( "nValue of i = %d", *( &i ) ) ;
}
The output of the above program would be:
Address of i = 65524
Value of i = 3
Value of i = 3
Note that printing the value of *( &i ) is same as printing the value of i.
The expression &i gives the address of the variable i. This address can be collected in a variable, by
saying,
j = &i ;
But remember that j is not an ordinary variable like any other integer variable and compiler must
provide it space in the memory. The following memory map would illustrate the contents of i and j.
As you can see, i’s value is 3 and j’s value is i’s address. But, we can’t use j in a program without
declaring it. And since j is a variable that contains the address of i, it is declared as,
int *j ;
This declaration tells the compiler that j will be used to store the address of an integer value. In
other words j points to an integer.
Here is a program that demonstrates the relationships we have been discussing.
main( )
{
int i = 3 ;
int *j ;
j = &i ;
printf ( "nAddress of i = %u", &i ) ;
printf ( "nAddress of i = %u", j ) ;
printf ( "nAddress of j = %u", &j ) ;
printf ( "nValue of j = %u", j ) ;
printf ( "nValue of i = %d", i ) ;
printf ( "nValue of i = %d", *( &i ) ) ;
printf ( "nValue of i = %d", *j ) ;
}
The output of the above program would be:
Address of i = 65524
Address of i = 65524
Address of j = 65522
Value of j = 65524
Value of i = 3
An Introduction to Pointers Intro to Programming
MUHAMMAD HAMMAD WASEEM 3
Value of i = 3
Value of i = 3
Pointers to Other Data Types
Look at the following declarations,
int *alpha ;
char *ch ;
float *s ;
Here, alpha, ch and s are declared as pointer variables, i.e. variables capable of holding
addresses. Remember that, addresses (location nos.) are always going to be whole numbers, therefore
pointers always contain whole numbers.
The declaration float *s does not mean that s is going to contain a floating-point value. What it
means is, s is going to contain the address of a floating-point value. Similarly, char *ch means that
ch is going to contain the address of a char value. Or in other words, the value at address stored in ch
is going to be a char.
Pointer towards a Pointer
The concept of pointers can be further extended. Pointer variable itself might be another pointer.
Thus, we now have a pointer that contains another pointer’s address. The following example should
make this point clear.
main( )
{
int i = 3, *j, **k ;
j = &i ;
k = &j ;
printf ( "nAddress of i = %u", &i ) ;
printf ( "nAddress of i = %u", j ) ;
printf ( "nAddress of i = %u", *k ) ;
printf ( "nAddress of j = %u", &j ) ;
printf ( "nAddress of j = %u", k ) ;
printf ( "nAddress of k = %u", &k ) ;
printf ( "nValue of j = %u", j ) ;
printf ( "nValue of k = %u", k ) ;
printf ( "nValue of i = %d", i ) ;
printf ( "nValue of i = %d", * ( &i ) ) ;
printf ( "nValue of i = %d", *j ) ;
printf ( "nValue of i = %d", **k ) ;
}
The output of the above program would be:
Address of i = 65524
Address of i = 65524
Address of i = 65524
Address of j = 65522
Address of j = 65522
Address of k = 65520
An Introduction to Pointers Intro to Programming
MUHAMMAD HAMMAD WASEEM 4
Value of j = 65524
Value of k = 65522
Value of i = 3
Value of i = 3
Value of i = 3
Value of i = 3
Remember that when you run this program the addresses that get printed might turn out to be
something different than the ones shown in the figure. However, with these addresses too the
relationship between i, j and k can be easily established.
Observe how the variables j and k have been declared,
int i, *j, **k ;
Here, i is an ordinary int, j is a pointer to an int (often called an integer pointer), whereas k is a
pointer to an integer pointer. We can extend the above program still further by creating a pointer to a
pointer to an integer pointer. In principle, you would agree that likewise there could exist a pointer to
a pointer to a pointer to a pointer to a pointer. There is no limit on how far can we go on extending this
definition.
Back to Function Calls
Having had the first tryst with pointers let us now get back to what we had originally set out to
learn—the two types of function calls—call by value and call by reference. Arguments can generally be
passed to functions in one of the two ways:
a) Sending the values of the arguments
b) Sending the addresses of the arguments
In the first method the ‘value’ of each of the actual arguments in the calling function is copied into
corresponding formal arguments of the called function. With this method the changes made to the
formal arguments in the called function have no effect on the values of actual arguments in the calling
function. The following program illustrates the ‘Call by Value’.
main( )
{
int a = 10, b = 20 ;
swapv ( a, b ) ;
printf ( "na = %d b = %d", a, b ) ;
}
swapv ( int x, int y )
{
int t ;
t = x ;
x = y ;
An Introduction to Pointers Intro to Programming
MUHAMMAD HAMMAD WASEEM 5
y = t ;
printf ( "nx = %d y = %d", x, y ) ;
}
The output of the above program would be:
x = 20 y = 10
a = 10 b = 20
Note that values of a and b remain unchanged even after exchanging the values of x and y.
In the second method (call by reference) the addresses of actual arguments in the calling function
are copied into formal arguments of the called function. This means that using these addresses we
would have an access to the actual arguments and hence we would be able to manipulate them. The
following program illustrates this fact.
main( )
{
int a = 10, b = 20 ;
swapr ( &a, &b ) ;
printf ( "na = %d b = %d", a, b ) ;
}
swapr( int *x, int *y )
{
int t ;
t = *x ;
*x = *y ;
*y = t ;
}
The output of the above program would be:
a = 20 b = 10
Note that this program manages to exchange the values of a and b using their addresses stored in x
and y.
Usually in C programming we make a call by value. This means that in general you cannot alter the
actual arguments. But if desired, it can always be achieved through a call by reference.
Using a call by reference intelligently we can make a function return more than one value at a time,
which is not possible ordinarily.
main( )
{
int radius ;
float area, perimeter ;
printf ( "nEnter radius of a circle " ) ;
scanf ( "%d", &radius ) ;
areaperi ( radius, &area, &perimeter ) ;
printf ( "Area = %f", area ) ;
printf ( "nPerimeter = %f", perimeter ) ;
}
areaperi ( int r, float *a, float *p )
{
An Introduction to Pointers Intro to Programming
MUHAMMAD HAMMAD WASEEM 6
*a = 3.14 * r * r ;
*p = 2 * 3.14 * r ;
}
And here is the output...
Enter radius of a circle 5
Area = 78.500000
Perimeter = 31.400000
Thus, we have been able to indirectly return two values from a called function, and hence, have
overcome the limitation of the return statement, which can return only one value from a function at a
time.
Conclusions
From the programs that we discussed here we can draw the following conclusions:
a) If we want that the value of an actual argument should not get changed in the function
being called, pass the actual argument by value.
b) If we want that the value of an actual argument should get changed in the function being
called, pass the actual argument by reference.
c) If a function is to be made to return more than one value at a time then return these values
indirectly by using a call by reference.

Mais conteúdo relacionado

Mais procurados

Maharishi University of Management (MSc Computer Science test questions)
Maharishi University of Management (MSc Computer Science test questions)Maharishi University of Management (MSc Computer Science test questions)
Maharishi University of Management (MSc Computer Science test questions)Dharma Kshetri
 
C programming(Part 1)
C programming(Part 1)C programming(Part 1)
C programming(Part 1)SURBHI SAROHA
 
Programming in C (part 2)
Programming in C (part 2)Programming in C (part 2)
Programming in C (part 2)SURBHI SAROHA
 
C programming(part 3)
C programming(part 3)C programming(part 3)
C programming(part 3)SURBHI SAROHA
 
[ITP - Lecture 04] Variables and Constants in C/C++
[ITP - Lecture 04] Variables and Constants in C/C++[ITP - Lecture 04] Variables and Constants in C/C++
[ITP - Lecture 04] Variables and Constants in C/C++Muhammad Hammad Waseem
 
46630497 fun-pointer-1
46630497 fun-pointer-146630497 fun-pointer-1
46630497 fun-pointer-1AmIt Prasad
 
C interview question answer 2
C interview question answer 2C interview question answer 2
C interview question answer 2Amit Kapoor
 
Functions and pointers_unit_4
Functions and pointers_unit_4Functions and pointers_unit_4
Functions and pointers_unit_4Saranya saran
 
C standard library functions
C standard library functionsC standard library functions
C standard library functionsVaishnavee Sharma
 
C aptitude scribd
C aptitude scribdC aptitude scribd
C aptitude scribdAmit Kapoor
 

Mais procurados (20)

Lecture 18 - Pointers
Lecture 18 - PointersLecture 18 - Pointers
Lecture 18 - Pointers
 
C Programming Unit-3
C Programming Unit-3C Programming Unit-3
C Programming Unit-3
 
Lecture 12 - Recursion
Lecture 12 - Recursion Lecture 12 - Recursion
Lecture 12 - Recursion
 
Lecture 10 - Control Structures 2
Lecture 10 - Control Structures 2Lecture 10 - Control Structures 2
Lecture 10 - Control Structures 2
 
Lecture 9- Control Structures 1
Lecture 9- Control Structures 1Lecture 9- Control Structures 1
Lecture 9- Control Structures 1
 
Maharishi University of Management (MSc Computer Science test questions)
Maharishi University of Management (MSc Computer Science test questions)Maharishi University of Management (MSc Computer Science test questions)
Maharishi University of Management (MSc Computer Science test questions)
 
Lecture 11 - Functions
Lecture 11 - FunctionsLecture 11 - Functions
Lecture 11 - Functions
 
C programming(Part 1)
C programming(Part 1)C programming(Part 1)
C programming(Part 1)
 
Programming in C (part 2)
Programming in C (part 2)Programming in C (part 2)
Programming in C (part 2)
 
C programming(part 3)
C programming(part 3)C programming(part 3)
C programming(part 3)
 
[ITP - Lecture 04] Variables and Constants in C/C++
[ITP - Lecture 04] Variables and Constants in C/C++[ITP - Lecture 04] Variables and Constants in C/C++
[ITP - Lecture 04] Variables and Constants in C/C++
 
Pointers in C language
Pointers  in  C languagePointers  in  C language
Pointers in C language
 
46630497 fun-pointer-1
46630497 fun-pointer-146630497 fun-pointer-1
46630497 fun-pointer-1
 
Lecture 14 - Scope Rules
Lecture 14 - Scope RulesLecture 14 - Scope Rules
Lecture 14 - Scope Rules
 
C interview question answer 2
C interview question answer 2C interview question answer 2
C interview question answer 2
 
Functions and pointers_unit_4
Functions and pointers_unit_4Functions and pointers_unit_4
Functions and pointers_unit_4
 
C standard library functions
C standard library functionsC standard library functions
C standard library functions
 
Lecture 6- Intorduction to C Programming
Lecture 6- Intorduction to C ProgrammingLecture 6- Intorduction to C Programming
Lecture 6- Intorduction to C Programming
 
C aptitude scribd
C aptitude scribdC aptitude scribd
C aptitude scribd
 
functions in C
functions in Cfunctions in C
functions in C
 

Semelhante a [ITP - Lecture 13] Introduction to Pointers

Semelhante a [ITP - Lecture 13] Introduction to Pointers (20)

Pointers
PointersPointers
Pointers
 
1. DSA - Introduction.pptx
1. DSA - Introduction.pptx1. DSA - Introduction.pptx
1. DSA - Introduction.pptx
 
Pointers.pptx
Pointers.pptxPointers.pptx
Pointers.pptx
 
Cs291 assignment solution
Cs291 assignment solutionCs291 assignment solution
Cs291 assignment solution
 
Ch 7-pointers
Ch 7-pointersCh 7-pointers
Ch 7-pointers
 
C important questions
C important questionsC important questions
C important questions
 
Pointers in C Language
Pointers in C LanguagePointers in C Language
Pointers in C Language
 
C Programming
C ProgrammingC Programming
C Programming
 
Functions and pointers_unit_4
Functions and pointers_unit_4Functions and pointers_unit_4
Functions and pointers_unit_4
 
C code examples
C code examplesC code examples
C code examples
 
C Programming Unit-4
C Programming Unit-4C Programming Unit-4
C Programming Unit-4
 
presentation_data_types_and_operators_1513499834_241350.pptx
presentation_data_types_and_operators_1513499834_241350.pptxpresentation_data_types_and_operators_1513499834_241350.pptx
presentation_data_types_and_operators_1513499834_241350.pptx
 
chapter-7 slide.pptx
chapter-7 slide.pptxchapter-7 slide.pptx
chapter-7 slide.pptx
 
C aptitude.2doc
C aptitude.2docC aptitude.2doc
C aptitude.2doc
 
Captitude 2doc-100627004318-phpapp01
Captitude 2doc-100627004318-phpapp01Captitude 2doc-100627004318-phpapp01
Captitude 2doc-100627004318-phpapp01
 
chapter-6 slide.pptx
chapter-6 slide.pptxchapter-6 slide.pptx
chapter-6 slide.pptx
 
C faq pdf
C faq pdfC faq pdf
C faq pdf
 
Types of function call
Types of function callTypes of function call
Types of function call
 
C function
C functionC function
C function
 
Functions
FunctionsFunctions
Functions
 

Mais de Muhammad Hammad Waseem

[ITP - Lecture 10] Switch Statement, Break and Continue Statement in C/C++
[ITP - Lecture 10] Switch Statement, Break and Continue Statement in C/C++[ITP - Lecture 10] Switch Statement, Break and Continue Statement in C/C++
[ITP - Lecture 10] Switch Statement, Break and Continue Statement in C/C++Muhammad Hammad Waseem
 
[ITP - Lecture 09] Conditional Operator in C/C++
[ITP - Lecture 09] Conditional Operator in C/C++[ITP - Lecture 09] Conditional Operator in C/C++
[ITP - Lecture 09] Conditional Operator in C/C++Muhammad Hammad Waseem
 
[ITP - Lecture 08] Decision Control Structures (If Statement)
[ITP - Lecture 08] Decision Control Structures (If Statement)[ITP - Lecture 08] Decision Control Structures (If Statement)
[ITP - Lecture 08] Decision Control Structures (If Statement)Muhammad Hammad Waseem
 
[ITP - Lecture 06] Operators, Arithmetic Expression and Order of Precedence
[ITP - Lecture 06] Operators, Arithmetic Expression and Order of Precedence[ITP - Lecture 06] Operators, Arithmetic Expression and Order of Precedence
[ITP - Lecture 06] Operators, Arithmetic Expression and Order of PrecedenceMuhammad Hammad Waseem
 
[ITP - Lecture 03] Introduction to C/C++
[ITP - Lecture 03] Introduction to C/C++[ITP - Lecture 03] Introduction to C/C++
[ITP - Lecture 03] Introduction to C/C++Muhammad Hammad Waseem
 
[ITP - Lecture 02] Steps to Create Program & Approaches of Programming
[ITP - Lecture 02] Steps to Create Program & Approaches of Programming[ITP - Lecture 02] Steps to Create Program & Approaches of Programming
[ITP - Lecture 02] Steps to Create Program & Approaches of ProgrammingMuhammad Hammad Waseem
 
[ITP - Lecture 01] Introduction to Programming & Different Programming Languages
[ITP - Lecture 01] Introduction to Programming & Different Programming Languages[ITP - Lecture 01] Introduction to Programming & Different Programming Languages
[ITP - Lecture 01] Introduction to Programming & Different Programming LanguagesMuhammad Hammad Waseem
 
[OOP - Lec 19] Static Member Functions
[OOP - Lec 19] Static Member Functions[OOP - Lec 19] Static Member Functions
[OOP - Lec 19] Static Member FunctionsMuhammad Hammad Waseem
 
[OOP - Lec 16,17] Objects as Function Parameter and ReturnType
[OOP - Lec 16,17] Objects as Function Parameter and ReturnType[OOP - Lec 16,17] Objects as Function Parameter and ReturnType
[OOP - Lec 16,17] Objects as Function Parameter and ReturnTypeMuhammad Hammad Waseem
 
[OOP - Lec 13,14,15] Constructors / Destructor and its Types
[OOP - Lec 13,14,15] Constructors / Destructor and its Types[OOP - Lec 13,14,15] Constructors / Destructor and its Types
[OOP - Lec 13,14,15] Constructors / Destructor and its TypesMuhammad Hammad Waseem
 
[OOP - Lec 09,10,11] Class Members & their Accessing
[OOP - Lec 09,10,11] Class Members & their Accessing[OOP - Lec 09,10,11] Class Members & their Accessing
[OOP - Lec 09,10,11] Class Members & their AccessingMuhammad Hammad Waseem
 
[OOP - Lec 08] Encapsulation (Information Hiding)
[OOP - Lec 08] Encapsulation (Information Hiding)[OOP - Lec 08] Encapsulation (Information Hiding)
[OOP - Lec 08] Encapsulation (Information Hiding)Muhammad Hammad Waseem
 
[OOP - Lec 04,05] Basic Building Blocks of OOP
[OOP - Lec 04,05] Basic Building Blocks of OOP[OOP - Lec 04,05] Basic Building Blocks of OOP
[OOP - Lec 04,05] Basic Building Blocks of OOPMuhammad Hammad Waseem
 

Mais de Muhammad Hammad Waseem (20)

[ITP - Lecture 10] Switch Statement, Break and Continue Statement in C/C++
[ITP - Lecture 10] Switch Statement, Break and Continue Statement in C/C++[ITP - Lecture 10] Switch Statement, Break and Continue Statement in C/C++
[ITP - Lecture 10] Switch Statement, Break and Continue Statement in C/C++
 
[ITP - Lecture 09] Conditional Operator in C/C++
[ITP - Lecture 09] Conditional Operator in C/C++[ITP - Lecture 09] Conditional Operator in C/C++
[ITP - Lecture 09] Conditional Operator in C/C++
 
[ITP - Lecture 08] Decision Control Structures (If Statement)
[ITP - Lecture 08] Decision Control Structures (If Statement)[ITP - Lecture 08] Decision Control Structures (If Statement)
[ITP - Lecture 08] Decision Control Structures (If Statement)
 
[ITP - Lecture 07] Comments in C/C++
[ITP - Lecture 07] Comments in C/C++[ITP - Lecture 07] Comments in C/C++
[ITP - Lecture 07] Comments in C/C++
 
[ITP - Lecture 06] Operators, Arithmetic Expression and Order of Precedence
[ITP - Lecture 06] Operators, Arithmetic Expression and Order of Precedence[ITP - Lecture 06] Operators, Arithmetic Expression and Order of Precedence
[ITP - Lecture 06] Operators, Arithmetic Expression and Order of Precedence
 
[ITP - Lecture 05] Datatypes
[ITP - Lecture 05] Datatypes[ITP - Lecture 05] Datatypes
[ITP - Lecture 05] Datatypes
 
[ITP - Lecture 03] Introduction to C/C++
[ITP - Lecture 03] Introduction to C/C++[ITP - Lecture 03] Introduction to C/C++
[ITP - Lecture 03] Introduction to C/C++
 
[ITP - Lecture 02] Steps to Create Program & Approaches of Programming
[ITP - Lecture 02] Steps to Create Program & Approaches of Programming[ITP - Lecture 02] Steps to Create Program & Approaches of Programming
[ITP - Lecture 02] Steps to Create Program & Approaches of Programming
 
[ITP - Lecture 01] Introduction to Programming & Different Programming Languages
[ITP - Lecture 01] Introduction to Programming & Different Programming Languages[ITP - Lecture 01] Introduction to Programming & Different Programming Languages
[ITP - Lecture 01] Introduction to Programming & Different Programming Languages
 
[OOP - Lec 20,21] Inheritance
[OOP - Lec 20,21] Inheritance[OOP - Lec 20,21] Inheritance
[OOP - Lec 20,21] Inheritance
 
[OOP - Lec 19] Static Member Functions
[OOP - Lec 19] Static Member Functions[OOP - Lec 19] Static Member Functions
[OOP - Lec 19] Static Member Functions
 
[OOP - Lec 18] Static Data Member
[OOP - Lec 18] Static Data Member[OOP - Lec 18] Static Data Member
[OOP - Lec 18] Static Data Member
 
[OOP - Lec 16,17] Objects as Function Parameter and ReturnType
[OOP - Lec 16,17] Objects as Function Parameter and ReturnType[OOP - Lec 16,17] Objects as Function Parameter and ReturnType
[OOP - Lec 16,17] Objects as Function Parameter and ReturnType
 
[OOP - Lec 13,14,15] Constructors / Destructor and its Types
[OOP - Lec 13,14,15] Constructors / Destructor and its Types[OOP - Lec 13,14,15] Constructors / Destructor and its Types
[OOP - Lec 13,14,15] Constructors / Destructor and its Types
 
[OOP - Lec 09,10,11] Class Members & their Accessing
[OOP - Lec 09,10,11] Class Members & their Accessing[OOP - Lec 09,10,11] Class Members & their Accessing
[OOP - Lec 09,10,11] Class Members & their Accessing
 
[OOP - Lec 08] Encapsulation (Information Hiding)
[OOP - Lec 08] Encapsulation (Information Hiding)[OOP - Lec 08] Encapsulation (Information Hiding)
[OOP - Lec 08] Encapsulation (Information Hiding)
 
[OOP - Lec 07] Access Specifiers
[OOP - Lec 07] Access Specifiers[OOP - Lec 07] Access Specifiers
[OOP - Lec 07] Access Specifiers
 
[OOP - Lec 06] Classes and Objects
[OOP - Lec 06] Classes and Objects[OOP - Lec 06] Classes and Objects
[OOP - Lec 06] Classes and Objects
 
[OOP - Lec 04,05] Basic Building Blocks of OOP
[OOP - Lec 04,05] Basic Building Blocks of OOP[OOP - Lec 04,05] Basic Building Blocks of OOP
[OOP - Lec 04,05] Basic Building Blocks of OOP
 
[OOP - Lec 03] Programming Paradigms
[OOP - Lec 03] Programming Paradigms[OOP - Lec 03] Programming Paradigms
[OOP - Lec 03] Programming Paradigms
 

Último

Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationnomboosow
 
Student login on Anyboli platform.helpin
Student login on Anyboli platform.helpinStudent login on Anyboli platform.helpin
Student login on Anyboli platform.helpinRaunakKeshri1
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactdawncurless
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfciinovamais
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfchloefrazer622
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxiammrhaywood
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhikauryashika82
 
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...fonyou31
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactPECB
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphThiyagu K
 
social pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajansocial pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajanpragatimahajan3
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13Steve Thomason
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityGeoBlogs
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfagholdier
 
Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Disha Kariya
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104misteraugie
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeThiyagu K
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdfQucHHunhnh
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Krashi Coaching
 

Último (20)

Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communication
 
Student login on Anyboli platform.helpin
Student login on Anyboli platform.helpinStudent login on Anyboli platform.helpin
Student login on Anyboli platform.helpin
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impact
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdf
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
 
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global Impact
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot Graph
 
social pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajansocial pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajan
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activity
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdf
 
Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and Mode
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
 

[ITP - Lecture 13] Introduction to Pointers

  • 1. An Introduction to Pointers Intro to Programming MUHAMMAD HAMMAD WASEEM 1 An Introduction to Pointers Which feature of C do beginners find most difficult to understand? The answer is easy: pointers. The difficulty beginners have with pointers has much to do with C’s pointer terminology than the actual concept. In our discussion of C pointers, therefore, we will try to avoid this difficulty by explaining pointers in terms of programming concepts we already understand. The first thing we want to do is explain the rationale of C’s pointer notation. Consider the declaration, int i = 3 ; This declaration tells the C compiler to: a) Reserve space in memory to hold the integer value. b) Associate the name i with this memory location. c) Store the value 3 at this location. We may represent i’s location in memory by the following memory map. We see that the computer has selected memory location 65524 as the place to store the value 3. The location number 65524 is not a number to be relied upon, because some other time the computer may choose a different location for storing the value 3. The important point is, i’s address in memory is a number. We can print this address number through the following program: main( ) { int i = 3 ; printf ( "nAddress of i = %u", &i ) ; printf ( "nValue of i = %d", i ) ; } The output of the above program would be: Address of i = 65524 Value of i = 3 Look at the first printf( ) statement carefully. ‘&’ used in this statement is C’s ‘address of’ operator. The expression &i returns the address of the variable i, which in this case happens to be 65524. The other pointer operator available in C is ‘*’, called ‘value at address’ operator. It gives the value stored at a particular address. The ‘value at address’ operator is also called ‘indirection’ operator. Observe carefully the output of the following program: main( ) { int i = 3 ; printf ( "nAddress of i = %u", &i ) ; printf ( "nValue of i = %d", i ) ;
  • 2. An Introduction to Pointers Intro to Programming MUHAMMAD HAMMAD WASEEM 2 printf ( "nValue of i = %d", *( &i ) ) ; } The output of the above program would be: Address of i = 65524 Value of i = 3 Value of i = 3 Note that printing the value of *( &i ) is same as printing the value of i. The expression &i gives the address of the variable i. This address can be collected in a variable, by saying, j = &i ; But remember that j is not an ordinary variable like any other integer variable and compiler must provide it space in the memory. The following memory map would illustrate the contents of i and j. As you can see, i’s value is 3 and j’s value is i’s address. But, we can’t use j in a program without declaring it. And since j is a variable that contains the address of i, it is declared as, int *j ; This declaration tells the compiler that j will be used to store the address of an integer value. In other words j points to an integer. Here is a program that demonstrates the relationships we have been discussing. main( ) { int i = 3 ; int *j ; j = &i ; printf ( "nAddress of i = %u", &i ) ; printf ( "nAddress of i = %u", j ) ; printf ( "nAddress of j = %u", &j ) ; printf ( "nValue of j = %u", j ) ; printf ( "nValue of i = %d", i ) ; printf ( "nValue of i = %d", *( &i ) ) ; printf ( "nValue of i = %d", *j ) ; } The output of the above program would be: Address of i = 65524 Address of i = 65524 Address of j = 65522 Value of j = 65524 Value of i = 3
  • 3. An Introduction to Pointers Intro to Programming MUHAMMAD HAMMAD WASEEM 3 Value of i = 3 Value of i = 3 Pointers to Other Data Types Look at the following declarations, int *alpha ; char *ch ; float *s ; Here, alpha, ch and s are declared as pointer variables, i.e. variables capable of holding addresses. Remember that, addresses (location nos.) are always going to be whole numbers, therefore pointers always contain whole numbers. The declaration float *s does not mean that s is going to contain a floating-point value. What it means is, s is going to contain the address of a floating-point value. Similarly, char *ch means that ch is going to contain the address of a char value. Or in other words, the value at address stored in ch is going to be a char. Pointer towards a Pointer The concept of pointers can be further extended. Pointer variable itself might be another pointer. Thus, we now have a pointer that contains another pointer’s address. The following example should make this point clear. main( ) { int i = 3, *j, **k ; j = &i ; k = &j ; printf ( "nAddress of i = %u", &i ) ; printf ( "nAddress of i = %u", j ) ; printf ( "nAddress of i = %u", *k ) ; printf ( "nAddress of j = %u", &j ) ; printf ( "nAddress of j = %u", k ) ; printf ( "nAddress of k = %u", &k ) ; printf ( "nValue of j = %u", j ) ; printf ( "nValue of k = %u", k ) ; printf ( "nValue of i = %d", i ) ; printf ( "nValue of i = %d", * ( &i ) ) ; printf ( "nValue of i = %d", *j ) ; printf ( "nValue of i = %d", **k ) ; } The output of the above program would be: Address of i = 65524 Address of i = 65524 Address of i = 65524 Address of j = 65522 Address of j = 65522 Address of k = 65520
  • 4. An Introduction to Pointers Intro to Programming MUHAMMAD HAMMAD WASEEM 4 Value of j = 65524 Value of k = 65522 Value of i = 3 Value of i = 3 Value of i = 3 Value of i = 3 Remember that when you run this program the addresses that get printed might turn out to be something different than the ones shown in the figure. However, with these addresses too the relationship between i, j and k can be easily established. Observe how the variables j and k have been declared, int i, *j, **k ; Here, i is an ordinary int, j is a pointer to an int (often called an integer pointer), whereas k is a pointer to an integer pointer. We can extend the above program still further by creating a pointer to a pointer to an integer pointer. In principle, you would agree that likewise there could exist a pointer to a pointer to a pointer to a pointer to a pointer. There is no limit on how far can we go on extending this definition. Back to Function Calls Having had the first tryst with pointers let us now get back to what we had originally set out to learn—the two types of function calls—call by value and call by reference. Arguments can generally be passed to functions in one of the two ways: a) Sending the values of the arguments b) Sending the addresses of the arguments In the first method the ‘value’ of each of the actual arguments in the calling function is copied into corresponding formal arguments of the called function. With this method the changes made to the formal arguments in the called function have no effect on the values of actual arguments in the calling function. The following program illustrates the ‘Call by Value’. main( ) { int a = 10, b = 20 ; swapv ( a, b ) ; printf ( "na = %d b = %d", a, b ) ; } swapv ( int x, int y ) { int t ; t = x ; x = y ;
  • 5. An Introduction to Pointers Intro to Programming MUHAMMAD HAMMAD WASEEM 5 y = t ; printf ( "nx = %d y = %d", x, y ) ; } The output of the above program would be: x = 20 y = 10 a = 10 b = 20 Note that values of a and b remain unchanged even after exchanging the values of x and y. In the second method (call by reference) the addresses of actual arguments in the calling function are copied into formal arguments of the called function. This means that using these addresses we would have an access to the actual arguments and hence we would be able to manipulate them. The following program illustrates this fact. main( ) { int a = 10, b = 20 ; swapr ( &a, &b ) ; printf ( "na = %d b = %d", a, b ) ; } swapr( int *x, int *y ) { int t ; t = *x ; *x = *y ; *y = t ; } The output of the above program would be: a = 20 b = 10 Note that this program manages to exchange the values of a and b using their addresses stored in x and y. Usually in C programming we make a call by value. This means that in general you cannot alter the actual arguments. But if desired, it can always be achieved through a call by reference. Using a call by reference intelligently we can make a function return more than one value at a time, which is not possible ordinarily. main( ) { int radius ; float area, perimeter ; printf ( "nEnter radius of a circle " ) ; scanf ( "%d", &radius ) ; areaperi ( radius, &area, &perimeter ) ; printf ( "Area = %f", area ) ; printf ( "nPerimeter = %f", perimeter ) ; } areaperi ( int r, float *a, float *p ) {
  • 6. An Introduction to Pointers Intro to Programming MUHAMMAD HAMMAD WASEEM 6 *a = 3.14 * r * r ; *p = 2 * 3.14 * r ; } And here is the output... Enter radius of a circle 5 Area = 78.500000 Perimeter = 31.400000 Thus, we have been able to indirectly return two values from a called function, and hence, have overcome the limitation of the return statement, which can return only one value from a function at a time. Conclusions From the programs that we discussed here we can draw the following conclusions: a) If we want that the value of an actual argument should not get changed in the function being called, pass the actual argument by value. b) If we want that the value of an actual argument should get changed in the function being called, pass the actual argument by reference. c) If a function is to be made to return more than one value at a time then return these values indirectly by using a call by reference.