SlideShare ist ein Scribd-Unternehmen logo
1 von 6
Downloaden Sie, um offline zu lesen
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.

Weitere Àhnliche Inhalte

Was ist angesagt?

C Programming Unit-3
C Programming Unit-3C Programming Unit-3
C Programming Unit-3Vikram Nandini
 
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
 
Lecture 6- Intorduction to C Programming
Lecture 6- Intorduction to C ProgrammingLecture 6- Intorduction to C Programming
Lecture 6- Intorduction to C ProgrammingMd. Imran Hossain Showrov
 
C aptitude scribd
C aptitude scribdC aptitude scribd
C aptitude scribdAmit Kapoor
 

Was ist angesagt? (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
 

Ähnlich wie [ITP - Lecture 13] Introduction to Pointers

1. DSA - Introduction.pptx
1. DSA - Introduction.pptx1. DSA - Introduction.pptx
1. DSA - Introduction.pptxhara69
 
Cs291 assignment solution
Cs291 assignment solutionCs291 assignment solution
Cs291 assignment solutionKuntal Bhowmick
 
C important questions
C important questionsC important questions
C important questionsJYOTI RANJAN PAL
 
Pointers in C Language
Pointers in C LanguagePointers in C Language
Pointers in C Languagemadan reddy
 
C Programming
C ProgrammingC Programming
C ProgrammingRaj vardhan
 
Functions and pointers_unit_4
Functions and pointers_unit_4Functions and pointers_unit_4
Functions and pointers_unit_4MKalpanaDevi
 
C Programming Unit-4
C Programming Unit-4C Programming Unit-4
C Programming Unit-4Vikram Nandini
 
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.pptxKrishanPalSingh39
 
chapter-7 slide.pptx
chapter-7 slide.pptxchapter-7 slide.pptx
chapter-7 slide.pptxcricketreview
 
C aptitude.2doc
C aptitude.2docC aptitude.2doc
C aptitude.2docSrikanth
 
chapter-6 slide.pptx
chapter-6 slide.pptxchapter-6 slide.pptx
chapter-6 slide.pptxcricketreview
 
C faq pdf
C faq pdfC faq pdf
C faq pdfDebiPanda
 
Types of function call
Types of function callTypes of function call
Types of function callArijitDhali
 

Ähnlich wie [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
 

Mehr von 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 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++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 18] Static Data Member
[OOP - Lec 18] Static Data Member[OOP - Lec 18] Static Data Member
[OOP - Lec 18] Static Data MemberMuhammad 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 07] Access Specifiers
[OOP - Lec 07] Access Specifiers[OOP - Lec 07] Access Specifiers
[OOP - Lec 07] Access SpecifiersMuhammad Hammad Waseem
 
[OOP - Lec 06] Classes and Objects
[OOP - Lec 06] Classes and Objects[OOP - Lec 06] Classes and Objects
[OOP - Lec 06] Classes and ObjectsMuhammad 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
 
[OOP - Lec 03] Programming Paradigms
[OOP - Lec 03] Programming Paradigms[OOP - Lec 03] Programming Paradigms
[OOP - Lec 03] Programming ParadigmsMuhammad Hammad Waseem
 

Mehr von 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
 

KĂŒrzlich hochgeladen

ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701bronxfugly43
 
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...pradhanghanshyam7136
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.pptRamjanShidvankar
 
Understanding Accommodations and Modifications
Understanding  Accommodations and ModificationsUnderstanding  Accommodations and Modifications
Understanding Accommodations and ModificationsMJDuyan
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxDenish Jangid
 
How to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POSHow to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POSCeline George
 
Sociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning ExhibitSociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning Exhibitjbellavia9
 
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
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxheathfieldcps1
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.christianmathematics
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsTechSoup
 
Unit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxUnit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxVishalSingh1417
 
Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxRamakrishna Reddy Bijjam
 
TỔNG ÔN TáșŹP THI VÀO LỚP 10 MÔN TIáșŸNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGở Â...
TỔNG ÔN TáșŹP THI VÀO LỚP 10 MÔN TIáșŸNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGở Â...TỔNG ÔN TáșŹP THI VÀO LỚP 10 MÔN TIáșŸNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGở Â...
TỔNG ÔN TáșŹP THI VÀO LỚP 10 MÔN TIáșŸNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGở Â...Nguyen Thanh Tu Collection
 
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17  How to Extend Models Using Mixin ClassesMixin Classes in Odoo 17  How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17 How to Extend Models Using Mixin ClassesCeline George
 
On National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsOn National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsMebane Rash
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingTechSoup
 
psychiatric nursing HISTORY COLLECTION .docx
psychiatric  nursing HISTORY  COLLECTION  .docxpsychiatric  nursing HISTORY  COLLECTION  .docx
psychiatric nursing HISTORY COLLECTION .docxPoojaSen20
 

KĂŒrzlich hochgeladen (20)

ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701
 
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.ppt
 
Understanding Accommodations and Modifications
Understanding  Accommodations and ModificationsUnderstanding  Accommodations and Modifications
Understanding Accommodations and Modifications
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
 
How to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POSHow to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POS
 
Sociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning ExhibitSociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning Exhibit
 
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
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.
 
Spatium Project Simulation student brief
Spatium Project Simulation student briefSpatium Project Simulation student brief
Spatium Project Simulation student brief
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The Basics
 
Unit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxUnit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptx
 
Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docx
 
TỔNG ÔN TáșŹP THI VÀO LỚP 10 MÔN TIáșŸNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGở Â...
TỔNG ÔN TáșŹP THI VÀO LỚP 10 MÔN TIáșŸNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGở Â...TỔNG ÔN TáșŹP THI VÀO LỚP 10 MÔN TIáșŸNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGở Â...
TỔNG ÔN TáșŹP THI VÀO LỚP 10 MÔN TIáșŸNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGở Â...
 
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17  How to Extend Models Using Mixin ClassesMixin Classes in Odoo 17  How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
 
On National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsOn National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan Fellows
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy Consulting
 
Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024
 
psychiatric nursing HISTORY COLLECTION .docx
psychiatric  nursing HISTORY  COLLECTION  .docxpsychiatric  nursing HISTORY  COLLECTION  .docx
psychiatric nursing HISTORY COLLECTION .docx
 

[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.