SlideShare a Scribd company logo
1 of 20
Programming in C
Pointer BasicsPointer Basics
What is a pointer
• In a generic sense, a “pointer” is anything thatIn a generic sense, a “pointer” is anything that
tells us where something can be found.tells us where something can be found.
– Addresses in the phone book
– URLs for webpages
– Road signs
Java Reference
• In Java, the name of an object is a reference toIn Java, the name of an object is a reference to
that object. Herethat object. Here ford is a reference to a Truckis a reference to a Truck
object. It contains the memory address at whichobject. It contains the memory address at which
the Truck object is stored.the Truck object is stored.
Truck ford = new Truck( );
• The syntax for using the reference is prettyThe syntax for using the reference is pretty
simple. Just use the “dot” notation.simple. Just use the “dot” notation.
ford.start( );
ford.drive( 23 );
ford.turn (LEFT);
1/14/10
What is a pointer ?
• In C, a pointer variable (or just “pointer”) isIn C, a pointer variable (or just “pointer”) is
similar to a reference in Java except thatsimilar to a reference in Java except that
– A pointer can contain the memory address of any
variable type (Java references only refer to objects)
– A primitive (int, char, float)
– An array
– A struct or union
– Dynamically allocated memory
– Another pointer
– A function
– There’s a lot of syntax required to create and use
pointers
1/14/10
Why Pointers?
• They allow you to refer to large data structures in aThey allow you to refer to large data structures in a
compact waycompact way
• They facilitate sharing between different parts of programsThey facilitate sharing between different parts of programs
• They make it possible to get new memory dynamically asThey make it possible to get new memory dynamically as
your program is runningyour program is running
• They make it easy to represent relationships among dataThey make it easy to represent relationships among data
items.items.
1/14/10
Pointer Caution
• They are a powerful low-level device.They are a powerful low-level device.
• Undisciplined use can be confusing and thus theUndisciplined use can be confusing and thus the
source of subtle, hard-to-find bugs.source of subtle, hard-to-find bugs.
– Program crashes
– Memory leaks
– Unpredictable results
1/14/10
C Pointer Variables
To declare a pointer variable, we must do two thingsTo declare a pointer variable, we must do two things
– Use the “*” (star) character to indicate that the variable
being defined is a pointer type.
– Indicate the type of variable to which the pointer will
point (the pointee). This is necessary because C
provides operations on pointers (e.g., *, ++, etc) whose
meaning depends on the type of the pointee.
• General declaration of a pointerGeneral declaration of a pointer
type *nameOfPointer;
1/14/10
Pointer Declaration
The declarationThe declaration
int *intPtr;
defines the variabledefines the variable intPtr to be a pointer to a variable ofto be a pointer to a variable of
typetype int.. intPtr will contain the memory address of somewill contain the memory address of some
int variable orvariable or int array. Read this declaration asarray. Read this declaration as
– “intPtr is a pointer to an int”, or equivalently
– “*intPtr is an int”
Caution -- Be careful when defining multiple variables on theCaution -- Be careful when defining multiple variables on the
same line. In this definitionsame line. In this definition
int *intPtr, intPtr2;
intPtr is a pointer to an int, but intPtr2 is not!
1/14/10
Pointer Operators
The two primary operators used with pointers areThe two primary operators used with pointers are
* (star) and(star) and && (ampersand)(ampersand)
– The * operator is used to define pointer variables and to
deference a pointer. “Dereferencing” a pointer means
to use the value of the pointee.
– The & operator gives the address of a variable.
Recall the use of & in scanf( )
1/14/10
Pointer Examples
int x = 1, y = 2, z[10];
int *ip; /* ip is a pointer to an int */
ip = &x; /* ip points to (contains the memory address of) x */
y = *ip; /* y is now 1, indirectly copied from x using ip */
*ip = 0; /* x is now 0 */
ip = &z[5]; /* ip now points to z[5] */
If ip points to x, then *ip can be used anywhere x can be used so in this
example *ip = *ip + 10; and x = x + 10; are equivalent
The * and & operators bind more tightly than arithmetic operators so
y = *ip + 1; takes the value of the variable to which ip points, adds 1
and assigns it to y
Similarly, the statements *ip += 1; and ++*ip; and (*ip)++; all increment
the variable to which ip points. (Note that the parenthesis are
necessary in the last statement; without them, the expression would
increment ip rather than what it points to since operators like * and
++ associate from right to left.)
1/14/10
Pointer and Variable types
• The type of a pointer and its pointee must matchThe type of a pointer and its pointee must match
int a = 42;
int *ip;
double d = 6.34;
double *dp;
ip = &a; /* ok -- types match */
dp = &d; /* ok */
ip = &d; /* compiler error -- type mismatch */
dp = &a; /* compiler error */
1/14/10
More Pointer Code
• Use ampersand (Use ampersand ( & ) to obtain the address of the pointee) to obtain the address of the pointee
• Use star (Use star ( * ) to get / change the value of the pointee) to get / change the value of the pointee
• UseUse %p to print the value of a pointer withto print the value of a pointer with printf( )
• What is the output from this code?What is the output from this code?
int a = 1, *ptr1;
/* show value and address of a
** and value of the pointer */
ptr1 = &a ;
printf("a = %d, &a = %p, ptr1 = %p, *ptr1 = %dn",
a, &a, ptr1, *ptr1) ;
/* change the value of a by dereferencing ptr1
** then print again */
*ptr1 = 35 ;
printf(“a = %d, &a = %p, ptr1 = %p, *ptr1 = %dn",
a, &a, ptr1, *ptr1) ;
1/14/10
NULL
• NULL is a special value which may be assigned to a pointerNULL is a special value which may be assigned to a pointer
• NULL indicates that this pointer does not point to anyNULL indicates that this pointer does not point to any
variable (there is no pointee)variable (there is no pointee)
• Often used when pointers are declaredOften used when pointers are declared
int *pInt = NULL;
• Often used as the return type of functions that return aOften used as the return type of functions that return a
pointer to indicate function failurepointer to indicate function failure
int *myPtr;
myPtr = myFunction( );
if (myPtr == NULL){
/* something bad happened */
}
• Dereferencing a pointer whose value is NULL will result inDereferencing a pointer whose value is NULL will result in
program terminationprogram termination..
1/14/10
Pointers and Function Arguments
• Since C passes all primitive function arguments “by value”Since C passes all primitive function arguments “by value”
there is no direct way for a function to alter a variable in thethere is no direct way for a function to alter a variable in the
calling code.calling code.
• This version of theThis version of the swap function doesn’t work.function doesn’t work. WHY NOT?WHY NOT?
/* calling swap from somewhere in main() */
int x = 42, y = 17;
Swap( x, y );
/* wrong version of swap */
void Swap (int a, int b)
{
int temp;
temp = a;
a = b;
b = temp;
}
1/14/10
A better swap( )
• The desired effect can be obtained by passing pointers toThe desired effect can be obtained by passing pointers to
the values to be exchanged.the values to be exchanged.
• This is a very common use of pointers.This is a very common use of pointers.
/* calling swap from somewhere in main( ) */
int x = 42, y = 17;
Swap( &x, &y );
/* correct version of swap */
void Swap (int *px, int *py)
{
int temp;
temp = *px;
*px = *py;
*py = temp;
}
1/14/10
More Pointer Function
Parameters
• Passing the address of variable(s) to a functionPassing the address of variable(s) to a function
can be used to have a function “return” multiplecan be used to have a function “return” multiple
values.values.
• The pointer arguments point to variables in theThe pointer arguments point to variables in the
calling code which are changed (“returned”) bycalling code which are changed (“returned”) by
the function.the function.
1/14/10
ConvertTime.c
void ConvertTime (int time, int *pHours, int *pMins)
{
*pHours = time / 60;
*pMins = time % 60;
}
int main( )
{
int time, hours, minutes;
printf("Enter a time duration in minutes: ");
scanf ("%d", &time);
ConvertTime (time, &hours, &minutes);
printf("HH:MM format: %d:%02dn", hours, minutes);
return 0;
}
1/14/10
An Exercise
• What is the output from this code?What is the output from this code?
void F (int a, int *b)
{
a = 7 ;
*b = a ;
b = &a ;
*b = 4 ;
printf("%d, %dn", a, *b) ;
}
int main()
{
int m = 3, n = 5;
F(m, &n) ;
printf("%d, %dn", m, n) ;
return 0;
}
4, 4
3, 7
1/14/10
Pointers to struct
/* define a struct for related student data */
typedef struct student {
char name[50];
char major [20];
double gpa;
} STUDENT;
STUDENT bob = {"Bob Smith", "Math", 3.77};
STUDENT sally = {"Sally", "CSEE", 4.0};
STUDENT *pStudent; /* pStudent is a "pointer to struct student" */
/* make pStudent point to bob */
pStudent = &bob;
/* use -> to access the members */
printf ("Bob's name: %sn", pStudent->name);
printf ("Bob's gpa : %fn", pStudent->gpa);
/* make pStudent point to sally */
pStudent = &sally;
printf ("Sally's name: %sn", pStudent->name);
printf ("Sally's gpa: %fn", pStudent->gpa);
Note too that the following are equivalent. Why??
pStudent->gpa and (*pStudent).gpa /* the parentheses are necessary */
9/24/10
Pointer to struct for functions
void PrintStudent(STUDENT *studentp)
{
printf(“Name : %sn”, studentp->name);
printf(“Major: %sn”, studentp->major);
printf(“GPA : %4.2f”, studentp->gpa);
}
Passing a pointer to a struct to a function is more
efficient than passing the struct itself. Why is
this true?

More Related Content

What's hot

Lecturer23 pointersin c.ppt
Lecturer23 pointersin c.pptLecturer23 pointersin c.ppt
Lecturer23 pointersin c.ppteShikshak
 
pointer, virtual function and polymorphism
pointer, virtual function and polymorphismpointer, virtual function and polymorphism
pointer, virtual function and polymorphismramya marichamy
 
Types of pointer in C
Types of pointer in CTypes of pointer in C
Types of pointer in Crgnikate
 
(3) cpp procedural programming
(3) cpp procedural programming(3) cpp procedural programming
(3) cpp procedural programmingNico Ludwig
 
Double pointer (pointer to pointer)
Double pointer (pointer to pointer)Double pointer (pointer to pointer)
Double pointer (pointer to pointer)sangrampatil81
 
Presentation 5th
Presentation 5thPresentation 5th
Presentation 5thConnex
 
Inline assembly language programs in c
Inline assembly language programs in cInline assembly language programs in c
Inline assembly language programs in cTech_MX
 
Pointers,virtual functions and polymorphism cpp
Pointers,virtual functions and polymorphism cppPointers,virtual functions and polymorphism cpp
Pointers,virtual functions and polymorphism cpprajshreemuthiah
 
Inline function
Inline functionInline function
Inline functionTech_MX
 
Functions in python
Functions in pythonFunctions in python
Functions in pythoncolorsof
 
VIT351 Software Development VI Unit1
VIT351 Software Development VI Unit1VIT351 Software Development VI Unit1
VIT351 Software Development VI Unit1YOGESH SINGH
 
Chapter 11 Function
Chapter 11 FunctionChapter 11 Function
Chapter 11 FunctionDeepak Singh
 

What's hot (20)

Lecturer23 pointersin c.ppt
Lecturer23 pointersin c.pptLecturer23 pointersin c.ppt
Lecturer23 pointersin c.ppt
 
Pointers in C
Pointers in CPointers in C
Pointers in C
 
pointer, virtual function and polymorphism
pointer, virtual function and polymorphismpointer, virtual function and polymorphism
pointer, virtual function and polymorphism
 
Pointers
PointersPointers
Pointers
 
Lk module5 pointers
Lk module5 pointersLk module5 pointers
Lk module5 pointers
 
Types of pointer in C
Types of pointer in CTypes of pointer in C
Types of pointer in C
 
(3) cpp procedural programming
(3) cpp procedural programming(3) cpp procedural programming
(3) cpp procedural programming
 
Double pointer (pointer to pointer)
Double pointer (pointer to pointer)Double pointer (pointer to pointer)
Double pointer (pointer to pointer)
 
Presentation 5th
Presentation 5thPresentation 5th
Presentation 5th
 
Pointers
PointersPointers
Pointers
 
Functions
FunctionsFunctions
Functions
 
Function
FunctionFunction
Function
 
Inline assembly language programs in c
Inline assembly language programs in cInline assembly language programs in c
Inline assembly language programs in c
 
Void pointer in c
Void pointer in cVoid pointer in c
Void pointer in c
 
Pointers,virtual functions and polymorphism cpp
Pointers,virtual functions and polymorphism cppPointers,virtual functions and polymorphism cpp
Pointers,virtual functions and polymorphism cpp
 
Inline function
Inline functionInline function
Inline function
 
Functions in python
Functions in pythonFunctions in python
Functions in python
 
VIT351 Software Development VI Unit1
VIT351 Software Development VI Unit1VIT351 Software Development VI Unit1
VIT351 Software Development VI Unit1
 
Chapter 11 Function
Chapter 11 FunctionChapter 11 Function
Chapter 11 Function
 
14 Jo P Feb 08
14 Jo P Feb 0814 Jo P Feb 08
14 Jo P Feb 08
 

Viewers also liked

Email là gì? 5 bí quyết giúp bạn giao tiếp qua email hiệu quả nhất
Email là gì? 5 bí quyết giúp bạn giao tiếp qua email hiệu quả nhấtEmail là gì? 5 bí quyết giúp bạn giao tiếp qua email hiệu quả nhất
Email là gì? 5 bí quyết giúp bạn giao tiếp qua email hiệu quả nhấtFreelancer
 
Kĩ năng giao tiếp qua email chuyên nghiệp
Kĩ năng giao tiếp qua email chuyên nghiệpKĩ năng giao tiếp qua email chuyên nghiệp
Kĩ năng giao tiếp qua email chuyên nghiệpTram Ngoc
 
Lập trình C cho 8051
Lập trình C cho 8051Lập trình C cho 8051
Lập trình C cho 8051chilacaiten
 
VI ĐIỀU KHIỂN 8051
VI ĐIỀU KHIỂN 8051VI ĐIỀU KHIỂN 8051
VI ĐIỀU KHIỂN 8051LE The Vinh
 
[Tiếng Anh] 600 Từ vựng Toeic
[Tiếng Anh] 600 Từ vựng Toeic[Tiếng Anh] 600 Từ vựng Toeic
[Tiếng Anh] 600 Từ vựng ToeicTươi Sama
 
Applying Semat - ứng dụng semat
Applying Semat - ứng dụng sematApplying Semat - ứng dụng semat
Applying Semat - ứng dụng sematNguyen Duong
 
Cơ sở lý luận và thực tiễn của công tác nghiên cứu dư luận xã hội (1)
Cơ sở lý luận và thực tiễn của công tác nghiên cứu dư luận xã hội (1)Cơ sở lý luận và thực tiễn của công tác nghiên cứu dư luận xã hội (1)
Cơ sở lý luận và thực tiễn của công tác nghiên cứu dư luận xã hội (1)DungUTC
 
Bạo lực cách mạng
Bạo lực cách mạngBạo lực cách mạng
Bạo lực cách mạngsen_sensen2003
 
Chuong 4 cohoc chatluu
Chuong 4 cohoc chatluuChuong 4 cohoc chatluu
Chuong 4 cohoc chatluuHarry Nguyen
 
Dia li 11 bai 11 khu vuc dong nam a tiet 1
Dia li 11 bai 11 khu vuc dong nam a tiet 1Dia li 11 bai 11 khu vuc dong nam a tiet 1
Dia li 11 bai 11 khu vuc dong nam a tiet 1lelynh221205
 
Fx3 g,fx3u,fx3uc series users manual positioning control edition
Fx3 g,fx3u,fx3uc series users manual   positioning control editionFx3 g,fx3u,fx3uc series users manual   positioning control edition
Fx3 g,fx3u,fx3uc series users manual positioning control editionphong279
 
Các nhóm phương pháp nghiên cứu khoa học nghiên cứu khoa học
Các nhóm phương pháp nghiên cứu khoa học nghiên cứu khoa họcCác nhóm phương pháp nghiên cứu khoa học nghiên cứu khoa học
Các nhóm phương pháp nghiên cứu khoa học nghiên cứu khoa họcDieu Dang
 
Quyết định tuyển dụng
Quyết định tuyển dụngQuyết định tuyển dụng
Quyết định tuyển dụngSnow Ball
 
Nlp lap trinh ngon ngu tu duy
Nlp lap trinh ngon ngu tu duyNlp lap trinh ngon ngu tu duy
Nlp lap trinh ngon ngu tu duyĐặng Vui
 
Bài tập CTDL và GT 4
Bài tập CTDL và GT 4Bài tập CTDL và GT 4
Bài tập CTDL và GT 4Hồ Lợi
 

Viewers also liked (20)

Email là gì? 5 bí quyết giúp bạn giao tiếp qua email hiệu quả nhất
Email là gì? 5 bí quyết giúp bạn giao tiếp qua email hiệu quả nhấtEmail là gì? 5 bí quyết giúp bạn giao tiếp qua email hiệu quả nhất
Email là gì? 5 bí quyết giúp bạn giao tiếp qua email hiệu quả nhất
 
Kĩ năng giao tiếp qua email chuyên nghiệp
Kĩ năng giao tiếp qua email chuyên nghiệpKĩ năng giao tiếp qua email chuyên nghiệp
Kĩ năng giao tiếp qua email chuyên nghiệp
 
Lập trình C cho 8051
Lập trình C cho 8051Lập trình C cho 8051
Lập trình C cho 8051
 
Spss
SpssSpss
Spss
 
83 2013-nd-cp
83 2013-nd-cp83 2013-nd-cp
83 2013-nd-cp
 
VI ĐIỀU KHIỂN 8051
VI ĐIỀU KHIỂN 8051VI ĐIỀU KHIỂN 8051
VI ĐIỀU KHIỂN 8051
 
[Tiếng Anh] 600 Từ vựng Toeic
[Tiếng Anh] 600 Từ vựng Toeic[Tiếng Anh] 600 Từ vựng Toeic
[Tiếng Anh] 600 Từ vựng Toeic
 
Applying Semat - ứng dụng semat
Applying Semat - ứng dụng sematApplying Semat - ứng dụng semat
Applying Semat - ứng dụng semat
 
Cơ sở lý luận và thực tiễn của công tác nghiên cứu dư luận xã hội (1)
Cơ sở lý luận và thực tiễn của công tác nghiên cứu dư luận xã hội (1)Cơ sở lý luận và thực tiễn của công tác nghiên cứu dư luận xã hội (1)
Cơ sở lý luận và thực tiễn của công tác nghiên cứu dư luận xã hội (1)
 
Option thuyet trinh
Option thuyet trinhOption thuyet trinh
Option thuyet trinh
 
Bạo lực cách mạng
Bạo lực cách mạngBạo lực cách mạng
Bạo lực cách mạng
 
Chuong 4 cohoc chatluu
Chuong 4 cohoc chatluuChuong 4 cohoc chatluu
Chuong 4 cohoc chatluu
 
Cau hoi dau tu
Cau hoi dau tuCau hoi dau tu
Cau hoi dau tu
 
Dia li 11 bai 11 khu vuc dong nam a tiet 1
Dia li 11 bai 11 khu vuc dong nam a tiet 1Dia li 11 bai 11 khu vuc dong nam a tiet 1
Dia li 11 bai 11 khu vuc dong nam a tiet 1
 
Fx3 g,fx3u,fx3uc series users manual positioning control edition
Fx3 g,fx3u,fx3uc series users manual   positioning control editionFx3 g,fx3u,fx3uc series users manual   positioning control edition
Fx3 g,fx3u,fx3uc series users manual positioning control edition
 
Các nhóm phương pháp nghiên cứu khoa học nghiên cứu khoa học
Các nhóm phương pháp nghiên cứu khoa học nghiên cứu khoa họcCác nhóm phương pháp nghiên cứu khoa học nghiên cứu khoa học
Các nhóm phương pháp nghiên cứu khoa học nghiên cứu khoa học
 
Quyết định tuyển dụng
Quyết định tuyển dụngQuyết định tuyển dụng
Quyết định tuyển dụng
 
Giáo trình sql server 2000
Giáo trình sql server 2000Giáo trình sql server 2000
Giáo trình sql server 2000
 
Nlp lap trinh ngon ngu tu duy
Nlp lap trinh ngon ngu tu duyNlp lap trinh ngon ngu tu duy
Nlp lap trinh ngon ngu tu duy
 
Bài tập CTDL và GT 4
Bài tập CTDL và GT 4Bài tập CTDL và GT 4
Bài tập CTDL và GT 4
 

Similar to C Pointer Basics Guide

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
 
btech-1picu-5pointerstructureunionandintrotofilehandling-150122010700-conver.ppt
btech-1picu-5pointerstructureunionandintrotofilehandling-150122010700-conver.pptbtech-1picu-5pointerstructureunionandintrotofilehandling-150122010700-conver.ppt
btech-1picu-5pointerstructureunionandintrotofilehandling-150122010700-conver.pptchintuyadav19
 
Pointers in c - Mohammad Salman
Pointers in c - Mohammad SalmanPointers in c - Mohammad Salman
Pointers in c - Mohammad SalmanMohammadSalman129
 
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
 
Pointers-Computer programming
Pointers-Computer programmingPointers-Computer programming
Pointers-Computer programmingnmahi96
 
Functions And Header Files In C++ | Bjarne stroustrup
Functions And Header Files In C++ | Bjarne stroustrupFunctions And Header Files In C++ | Bjarne stroustrup
Functions And Header Files In C++ | Bjarne stroustrupSyedHaroonShah4
 
VIT351 Software Development VI Unit3
VIT351 Software Development VI Unit3VIT351 Software Development VI Unit3
VIT351 Software Development VI Unit3YOGESH SINGH
 
Advanced C programming
Advanced C programmingAdvanced C programming
Advanced C programmingClaus Wu
 
EASY UNDERSTANDING OF POINTERS IN C LANGUAGE.pdf
EASY UNDERSTANDING OF POINTERS IN C LANGUAGE.pdfEASY UNDERSTANDING OF POINTERS IN C LANGUAGE.pdf
EASY UNDERSTANDING OF POINTERS IN C LANGUAGE.pdfsudhakargeruganti
 
CSEG1001 Unit 4 Functions and Pointers
CSEG1001 Unit 4 Functions and PointersCSEG1001 Unit 4 Functions and Pointers
CSEG1001 Unit 4 Functions and PointersDhiviya Rose
 
Pointers and Array, pointer and String.pptx
Pointers and Array, pointer and String.pptxPointers and Array, pointer and String.pptx
Pointers and Array, pointer and String.pptxAnanthi Palanisamy
 
Pointers Refrences & dynamic memory allocation in C++
Pointers Refrences & dynamic memory allocation in C++Pointers Refrences & dynamic memory allocation in C++
Pointers Refrences & dynamic memory allocation in C++Gamindu Udayanga
 

Similar to C Pointer Basics Guide (20)

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
 
btech-1picu-5pointerstructureunionandintrotofilehandling-150122010700-conver.ppt
btech-1picu-5pointerstructureunionandintrotofilehandling-150122010700-conver.pptbtech-1picu-5pointerstructureunionandintrotofilehandling-150122010700-conver.ppt
btech-1picu-5pointerstructureunionandintrotofilehandling-150122010700-conver.ppt
 
Pointers in c - Mohammad Salman
Pointers in c - Mohammad SalmanPointers in c - Mohammad Salman
Pointers in c - Mohammad Salman
 
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
 
Pointers-Computer programming
Pointers-Computer programmingPointers-Computer programming
Pointers-Computer programming
 
pointers.pptx
pointers.pptxpointers.pptx
pointers.pptx
 
Functions And Header Files In C++ | Bjarne stroustrup
Functions And Header Files In C++ | Bjarne stroustrupFunctions And Header Files In C++ | Bjarne stroustrup
Functions And Header Files In C++ | Bjarne stroustrup
 
VIT351 Software Development VI Unit3
VIT351 Software Development VI Unit3VIT351 Software Development VI Unit3
VIT351 Software Development VI Unit3
 
Advanced C programming
Advanced C programmingAdvanced C programming
Advanced C programming
 
PSPC--UNIT-5.pdf
PSPC--UNIT-5.pdfPSPC--UNIT-5.pdf
PSPC--UNIT-5.pdf
 
EASY UNDERSTANDING OF POINTERS IN C LANGUAGE.pdf
EASY UNDERSTANDING OF POINTERS IN C LANGUAGE.pdfEASY UNDERSTANDING OF POINTERS IN C LANGUAGE.pdf
EASY UNDERSTANDING OF POINTERS IN C LANGUAGE.pdf
 
C programming
C programmingC programming
C programming
 
Advanced pointers
Advanced pointersAdvanced pointers
Advanced pointers
 
CSEG1001 Unit 4 Functions and Pointers
CSEG1001 Unit 4 Functions and PointersCSEG1001 Unit 4 Functions and Pointers
CSEG1001 Unit 4 Functions and Pointers
 
Pointers
PointersPointers
Pointers
 
Pointers and Array, pointer and String.pptx
Pointers and Array, pointer and String.pptxPointers and Array, pointer and String.pptx
Pointers and Array, pointer and String.pptx
 
COM1407: Working with Pointers
COM1407: Working with PointersCOM1407: Working with Pointers
COM1407: Working with Pointers
 
Pointers Refrences & dynamic memory allocation in C++
Pointers Refrences & dynamic memory allocation in C++Pointers Refrences & dynamic memory allocation in C++
Pointers Refrences & dynamic memory allocation in C++
 
C programming session8
C programming  session8C programming  session8
C programming session8
 
C programming session8
C programming  session8C programming  session8
C programming session8
 

Recently uploaded

定制(UAL学位证)英国伦敦艺术大学毕业证成绩单原版一比一
定制(UAL学位证)英国伦敦艺术大学毕业证成绩单原版一比一定制(UAL学位证)英国伦敦艺术大学毕业证成绩单原版一比一
定制(UAL学位证)英国伦敦艺术大学毕业证成绩单原版一比一Fs
 
VIP Kolkata Call Girls Salt Lake 8250192130 Available With Room
VIP Kolkata Call Girls Salt Lake 8250192130 Available With RoomVIP Kolkata Call Girls Salt Lake 8250192130 Available With Room
VIP Kolkata Call Girls Salt Lake 8250192130 Available With Roomgirls4nights
 
Russian Call girls in Dubai +971563133746 Dubai Call girls
Russian  Call girls in Dubai +971563133746 Dubai  Call girlsRussian  Call girls in Dubai +971563133746 Dubai  Call girls
Russian Call girls in Dubai +971563133746 Dubai Call girlsstephieert
 
VIP Call Girls Pune Madhuri 8617697112 Independent Escort Service Pune
VIP Call Girls Pune Madhuri 8617697112 Independent Escort Service PuneVIP Call Girls Pune Madhuri 8617697112 Independent Escort Service Pune
VIP Call Girls Pune Madhuri 8617697112 Independent Escort Service PuneCall girls in Ahmedabad High profile
 
Complet Documnetation for Smart Assistant Application for Disabled Person
Complet Documnetation   for Smart Assistant Application for Disabled PersonComplet Documnetation   for Smart Assistant Application for Disabled Person
Complet Documnetation for Smart Assistant Application for Disabled Personfurqan222004
 
DDoS In Oceania and the Pacific, presented by Dave Phelan at NZNOG 2024
DDoS In Oceania and the Pacific, presented by Dave Phelan at NZNOG 2024DDoS In Oceania and the Pacific, presented by Dave Phelan at NZNOG 2024
DDoS In Oceania and the Pacific, presented by Dave Phelan at NZNOG 2024APNIC
 
Call Girls In Saket Delhi 💯Call Us 🔝8264348440🔝
Call Girls In Saket Delhi 💯Call Us 🔝8264348440🔝Call Girls In Saket Delhi 💯Call Us 🔝8264348440🔝
Call Girls In Saket Delhi 💯Call Us 🔝8264348440🔝soniya singh
 
VIP Kolkata Call Girl Alambazar 👉 8250192130 Available With Room
VIP Kolkata Call Girl Alambazar 👉 8250192130  Available With RoomVIP Kolkata Call Girl Alambazar 👉 8250192130  Available With Room
VIP Kolkata Call Girl Alambazar 👉 8250192130 Available With Roomdivyansh0kumar0
 
How is AI changing journalism? (v. April 2024)
How is AI changing journalism? (v. April 2024)How is AI changing journalism? (v. April 2024)
How is AI changing journalism? (v. April 2024)Damian Radcliffe
 
VIP 7001035870 Find & Meet Hyderabad Call Girls Dilsukhnagar high-profile Cal...
VIP 7001035870 Find & Meet Hyderabad Call Girls Dilsukhnagar high-profile Cal...VIP 7001035870 Find & Meet Hyderabad Call Girls Dilsukhnagar high-profile Cal...
VIP 7001035870 Find & Meet Hyderabad Call Girls Dilsukhnagar high-profile Cal...aditipandeya
 
AWS Community DAY Albertini-Ellan Cloud Security (1).pptx
AWS Community DAY Albertini-Ellan Cloud Security (1).pptxAWS Community DAY Albertini-Ellan Cloud Security (1).pptx
AWS Community DAY Albertini-Ellan Cloud Security (1).pptxellan12
 
GDG Cloud Southlake 32: Kyle Hettinger: Demystifying the Dark Web
GDG Cloud Southlake 32: Kyle Hettinger: Demystifying the Dark WebGDG Cloud Southlake 32: Kyle Hettinger: Demystifying the Dark Web
GDG Cloud Southlake 32: Kyle Hettinger: Demystifying the Dark WebJames Anderson
 
定制(CC毕业证书)美国美国社区大学毕业证成绩单原版一比一
定制(CC毕业证书)美国美国社区大学毕业证成绩单原版一比一定制(CC毕业证书)美国美国社区大学毕业证成绩单原版一比一
定制(CC毕业证书)美国美国社区大学毕业证成绩单原版一比一3sw2qly1
 
VIP Kolkata Call Girl Kestopur 👉 8250192130 Available With Room
VIP Kolkata Call Girl Kestopur 👉 8250192130  Available With RoomVIP Kolkata Call Girl Kestopur 👉 8250192130  Available With Room
VIP Kolkata Call Girl Kestopur 👉 8250192130 Available With Roomdivyansh0kumar0
 
Low Rate Young Call Girls in Sector 63 Mamura Noida ✔️☆9289244007✔️☆ Female E...
Low Rate Young Call Girls in Sector 63 Mamura Noida ✔️☆9289244007✔️☆ Female E...Low Rate Young Call Girls in Sector 63 Mamura Noida ✔️☆9289244007✔️☆ Female E...
Low Rate Young Call Girls in Sector 63 Mamura Noida ✔️☆9289244007✔️☆ Female E...SofiyaSharma5
 
✂️ 👅 Independent Andheri Escorts With Room Vashi Call Girls 💃 9004004663
✂️ 👅 Independent Andheri Escorts With Room Vashi Call Girls 💃 9004004663✂️ 👅 Independent Andheri Escorts With Room Vashi Call Girls 💃 9004004663
✂️ 👅 Independent Andheri Escorts With Room Vashi Call Girls 💃 9004004663Call Girls Mumbai
 
Best VIP Call Girls Noida Sector 75 Call Me: 8448380779
Best VIP Call Girls Noida Sector 75 Call Me: 8448380779Best VIP Call Girls Noida Sector 75 Call Me: 8448380779
Best VIP Call Girls Noida Sector 75 Call Me: 8448380779Delhi Call girls
 
Call Girls in East Of Kailash 9711199171 Delhi Enjoy Call Girls With Our Escorts
Call Girls in East Of Kailash 9711199171 Delhi Enjoy Call Girls With Our EscortsCall Girls in East Of Kailash 9711199171 Delhi Enjoy Call Girls With Our Escorts
Call Girls in East Of Kailash 9711199171 Delhi Enjoy Call Girls With Our Escortsindian call girls near you
 

Recently uploaded (20)

定制(UAL学位证)英国伦敦艺术大学毕业证成绩单原版一比一
定制(UAL学位证)英国伦敦艺术大学毕业证成绩单原版一比一定制(UAL学位证)英国伦敦艺术大学毕业证成绩单原版一比一
定制(UAL学位证)英国伦敦艺术大学毕业证成绩单原版一比一
 
VIP Kolkata Call Girls Salt Lake 8250192130 Available With Room
VIP Kolkata Call Girls Salt Lake 8250192130 Available With RoomVIP Kolkata Call Girls Salt Lake 8250192130 Available With Room
VIP Kolkata Call Girls Salt Lake 8250192130 Available With Room
 
Rohini Sector 26 Call Girls Delhi 9999965857 @Sabina Saikh No Advance
Rohini Sector 26 Call Girls Delhi 9999965857 @Sabina Saikh No AdvanceRohini Sector 26 Call Girls Delhi 9999965857 @Sabina Saikh No Advance
Rohini Sector 26 Call Girls Delhi 9999965857 @Sabina Saikh No Advance
 
Russian Call girls in Dubai +971563133746 Dubai Call girls
Russian  Call girls in Dubai +971563133746 Dubai  Call girlsRussian  Call girls in Dubai +971563133746 Dubai  Call girls
Russian Call girls in Dubai +971563133746 Dubai Call girls
 
VIP Call Girls Pune Madhuri 8617697112 Independent Escort Service Pune
VIP Call Girls Pune Madhuri 8617697112 Independent Escort Service PuneVIP Call Girls Pune Madhuri 8617697112 Independent Escort Service Pune
VIP Call Girls Pune Madhuri 8617697112 Independent Escort Service Pune
 
Complet Documnetation for Smart Assistant Application for Disabled Person
Complet Documnetation   for Smart Assistant Application for Disabled PersonComplet Documnetation   for Smart Assistant Application for Disabled Person
Complet Documnetation for Smart Assistant Application for Disabled Person
 
DDoS In Oceania and the Pacific, presented by Dave Phelan at NZNOG 2024
DDoS In Oceania and the Pacific, presented by Dave Phelan at NZNOG 2024DDoS In Oceania and the Pacific, presented by Dave Phelan at NZNOG 2024
DDoS In Oceania and the Pacific, presented by Dave Phelan at NZNOG 2024
 
Call Girls In Saket Delhi 💯Call Us 🔝8264348440🔝
Call Girls In Saket Delhi 💯Call Us 🔝8264348440🔝Call Girls In Saket Delhi 💯Call Us 🔝8264348440🔝
Call Girls In Saket Delhi 💯Call Us 🔝8264348440🔝
 
Rohini Sector 6 Call Girls Delhi 9999965857 @Sabina Saikh No Advance
Rohini Sector 6 Call Girls Delhi 9999965857 @Sabina Saikh No AdvanceRohini Sector 6 Call Girls Delhi 9999965857 @Sabina Saikh No Advance
Rohini Sector 6 Call Girls Delhi 9999965857 @Sabina Saikh No Advance
 
VIP Kolkata Call Girl Alambazar 👉 8250192130 Available With Room
VIP Kolkata Call Girl Alambazar 👉 8250192130  Available With RoomVIP Kolkata Call Girl Alambazar 👉 8250192130  Available With Room
VIP Kolkata Call Girl Alambazar 👉 8250192130 Available With Room
 
How is AI changing journalism? (v. April 2024)
How is AI changing journalism? (v. April 2024)How is AI changing journalism? (v. April 2024)
How is AI changing journalism? (v. April 2024)
 
VIP 7001035870 Find & Meet Hyderabad Call Girls Dilsukhnagar high-profile Cal...
VIP 7001035870 Find & Meet Hyderabad Call Girls Dilsukhnagar high-profile Cal...VIP 7001035870 Find & Meet Hyderabad Call Girls Dilsukhnagar high-profile Cal...
VIP 7001035870 Find & Meet Hyderabad Call Girls Dilsukhnagar high-profile Cal...
 
AWS Community DAY Albertini-Ellan Cloud Security (1).pptx
AWS Community DAY Albertini-Ellan Cloud Security (1).pptxAWS Community DAY Albertini-Ellan Cloud Security (1).pptx
AWS Community DAY Albertini-Ellan Cloud Security (1).pptx
 
GDG Cloud Southlake 32: Kyle Hettinger: Demystifying the Dark Web
GDG Cloud Southlake 32: Kyle Hettinger: Demystifying the Dark WebGDG Cloud Southlake 32: Kyle Hettinger: Demystifying the Dark Web
GDG Cloud Southlake 32: Kyle Hettinger: Demystifying the Dark Web
 
定制(CC毕业证书)美国美国社区大学毕业证成绩单原版一比一
定制(CC毕业证书)美国美国社区大学毕业证成绩单原版一比一定制(CC毕业证书)美国美国社区大学毕业证成绩单原版一比一
定制(CC毕业证书)美国美国社区大学毕业证成绩单原版一比一
 
VIP Kolkata Call Girl Kestopur 👉 8250192130 Available With Room
VIP Kolkata Call Girl Kestopur 👉 8250192130  Available With RoomVIP Kolkata Call Girl Kestopur 👉 8250192130  Available With Room
VIP Kolkata Call Girl Kestopur 👉 8250192130 Available With Room
 
Low Rate Young Call Girls in Sector 63 Mamura Noida ✔️☆9289244007✔️☆ Female E...
Low Rate Young Call Girls in Sector 63 Mamura Noida ✔️☆9289244007✔️☆ Female E...Low Rate Young Call Girls in Sector 63 Mamura Noida ✔️☆9289244007✔️☆ Female E...
Low Rate Young Call Girls in Sector 63 Mamura Noida ✔️☆9289244007✔️☆ Female E...
 
✂️ 👅 Independent Andheri Escorts With Room Vashi Call Girls 💃 9004004663
✂️ 👅 Independent Andheri Escorts With Room Vashi Call Girls 💃 9004004663✂️ 👅 Independent Andheri Escorts With Room Vashi Call Girls 💃 9004004663
✂️ 👅 Independent Andheri Escorts With Room Vashi Call Girls 💃 9004004663
 
Best VIP Call Girls Noida Sector 75 Call Me: 8448380779
Best VIP Call Girls Noida Sector 75 Call Me: 8448380779Best VIP Call Girls Noida Sector 75 Call Me: 8448380779
Best VIP Call Girls Noida Sector 75 Call Me: 8448380779
 
Call Girls in East Of Kailash 9711199171 Delhi Enjoy Call Girls With Our Escorts
Call Girls in East Of Kailash 9711199171 Delhi Enjoy Call Girls With Our EscortsCall Girls in East Of Kailash 9711199171 Delhi Enjoy Call Girls With Our Escorts
Call Girls in East Of Kailash 9711199171 Delhi Enjoy Call Girls With Our Escorts
 

C Pointer Basics Guide

  • 1. Programming in C Pointer BasicsPointer Basics
  • 2. What is a pointer • In a generic sense, a “pointer” is anything thatIn a generic sense, a “pointer” is anything that tells us where something can be found.tells us where something can be found. – Addresses in the phone book – URLs for webpages – Road signs
  • 3. Java Reference • In Java, the name of an object is a reference toIn Java, the name of an object is a reference to that object. Herethat object. Here ford is a reference to a Truckis a reference to a Truck object. It contains the memory address at whichobject. It contains the memory address at which the Truck object is stored.the Truck object is stored. Truck ford = new Truck( ); • The syntax for using the reference is prettyThe syntax for using the reference is pretty simple. Just use the “dot” notation.simple. Just use the “dot” notation. ford.start( ); ford.drive( 23 ); ford.turn (LEFT);
  • 4. 1/14/10 What is a pointer ? • In C, a pointer variable (or just “pointer”) isIn C, a pointer variable (or just “pointer”) is similar to a reference in Java except thatsimilar to a reference in Java except that – A pointer can contain the memory address of any variable type (Java references only refer to objects) – A primitive (int, char, float) – An array – A struct or union – Dynamically allocated memory – Another pointer – A function – There’s a lot of syntax required to create and use pointers
  • 5. 1/14/10 Why Pointers? • They allow you to refer to large data structures in aThey allow you to refer to large data structures in a compact waycompact way • They facilitate sharing between different parts of programsThey facilitate sharing between different parts of programs • They make it possible to get new memory dynamically asThey make it possible to get new memory dynamically as your program is runningyour program is running • They make it easy to represent relationships among dataThey make it easy to represent relationships among data items.items.
  • 6. 1/14/10 Pointer Caution • They are a powerful low-level device.They are a powerful low-level device. • Undisciplined use can be confusing and thus theUndisciplined use can be confusing and thus the source of subtle, hard-to-find bugs.source of subtle, hard-to-find bugs. – Program crashes – Memory leaks – Unpredictable results
  • 7. 1/14/10 C Pointer Variables To declare a pointer variable, we must do two thingsTo declare a pointer variable, we must do two things – Use the “*” (star) character to indicate that the variable being defined is a pointer type. – Indicate the type of variable to which the pointer will point (the pointee). This is necessary because C provides operations on pointers (e.g., *, ++, etc) whose meaning depends on the type of the pointee. • General declaration of a pointerGeneral declaration of a pointer type *nameOfPointer;
  • 8. 1/14/10 Pointer Declaration The declarationThe declaration int *intPtr; defines the variabledefines the variable intPtr to be a pointer to a variable ofto be a pointer to a variable of typetype int.. intPtr will contain the memory address of somewill contain the memory address of some int variable orvariable or int array. Read this declaration asarray. Read this declaration as – “intPtr is a pointer to an int”, or equivalently – “*intPtr is an int” Caution -- Be careful when defining multiple variables on theCaution -- Be careful when defining multiple variables on the same line. In this definitionsame line. In this definition int *intPtr, intPtr2; intPtr is a pointer to an int, but intPtr2 is not!
  • 9. 1/14/10 Pointer Operators The two primary operators used with pointers areThe two primary operators used with pointers are * (star) and(star) and && (ampersand)(ampersand) – The * operator is used to define pointer variables and to deference a pointer. “Dereferencing” a pointer means to use the value of the pointee. – The & operator gives the address of a variable. Recall the use of & in scanf( )
  • 10. 1/14/10 Pointer Examples int x = 1, y = 2, z[10]; int *ip; /* ip is a pointer to an int */ ip = &x; /* ip points to (contains the memory address of) x */ y = *ip; /* y is now 1, indirectly copied from x using ip */ *ip = 0; /* x is now 0 */ ip = &z[5]; /* ip now points to z[5] */ If ip points to x, then *ip can be used anywhere x can be used so in this example *ip = *ip + 10; and x = x + 10; are equivalent The * and & operators bind more tightly than arithmetic operators so y = *ip + 1; takes the value of the variable to which ip points, adds 1 and assigns it to y Similarly, the statements *ip += 1; and ++*ip; and (*ip)++; all increment the variable to which ip points. (Note that the parenthesis are necessary in the last statement; without them, the expression would increment ip rather than what it points to since operators like * and ++ associate from right to left.)
  • 11. 1/14/10 Pointer and Variable types • The type of a pointer and its pointee must matchThe type of a pointer and its pointee must match int a = 42; int *ip; double d = 6.34; double *dp; ip = &a; /* ok -- types match */ dp = &d; /* ok */ ip = &d; /* compiler error -- type mismatch */ dp = &a; /* compiler error */
  • 12. 1/14/10 More Pointer Code • Use ampersand (Use ampersand ( & ) to obtain the address of the pointee) to obtain the address of the pointee • Use star (Use star ( * ) to get / change the value of the pointee) to get / change the value of the pointee • UseUse %p to print the value of a pointer withto print the value of a pointer with printf( ) • What is the output from this code?What is the output from this code? int a = 1, *ptr1; /* show value and address of a ** and value of the pointer */ ptr1 = &a ; printf("a = %d, &a = %p, ptr1 = %p, *ptr1 = %dn", a, &a, ptr1, *ptr1) ; /* change the value of a by dereferencing ptr1 ** then print again */ *ptr1 = 35 ; printf(“a = %d, &a = %p, ptr1 = %p, *ptr1 = %dn", a, &a, ptr1, *ptr1) ;
  • 13. 1/14/10 NULL • NULL is a special value which may be assigned to a pointerNULL is a special value which may be assigned to a pointer • NULL indicates that this pointer does not point to anyNULL indicates that this pointer does not point to any variable (there is no pointee)variable (there is no pointee) • Often used when pointers are declaredOften used when pointers are declared int *pInt = NULL; • Often used as the return type of functions that return aOften used as the return type of functions that return a pointer to indicate function failurepointer to indicate function failure int *myPtr; myPtr = myFunction( ); if (myPtr == NULL){ /* something bad happened */ } • Dereferencing a pointer whose value is NULL will result inDereferencing a pointer whose value is NULL will result in program terminationprogram termination..
  • 14. 1/14/10 Pointers and Function Arguments • Since C passes all primitive function arguments “by value”Since C passes all primitive function arguments “by value” there is no direct way for a function to alter a variable in thethere is no direct way for a function to alter a variable in the calling code.calling code. • This version of theThis version of the swap function doesn’t work.function doesn’t work. WHY NOT?WHY NOT? /* calling swap from somewhere in main() */ int x = 42, y = 17; Swap( x, y ); /* wrong version of swap */ void Swap (int a, int b) { int temp; temp = a; a = b; b = temp; }
  • 15. 1/14/10 A better swap( ) • The desired effect can be obtained by passing pointers toThe desired effect can be obtained by passing pointers to the values to be exchanged.the values to be exchanged. • This is a very common use of pointers.This is a very common use of pointers. /* calling swap from somewhere in main( ) */ int x = 42, y = 17; Swap( &x, &y ); /* correct version of swap */ void Swap (int *px, int *py) { int temp; temp = *px; *px = *py; *py = temp; }
  • 16. 1/14/10 More Pointer Function Parameters • Passing the address of variable(s) to a functionPassing the address of variable(s) to a function can be used to have a function “return” multiplecan be used to have a function “return” multiple values.values. • The pointer arguments point to variables in theThe pointer arguments point to variables in the calling code which are changed (“returned”) bycalling code which are changed (“returned”) by the function.the function.
  • 17. 1/14/10 ConvertTime.c void ConvertTime (int time, int *pHours, int *pMins) { *pHours = time / 60; *pMins = time % 60; } int main( ) { int time, hours, minutes; printf("Enter a time duration in minutes: "); scanf ("%d", &time); ConvertTime (time, &hours, &minutes); printf("HH:MM format: %d:%02dn", hours, minutes); return 0; }
  • 18. 1/14/10 An Exercise • What is the output from this code?What is the output from this code? void F (int a, int *b) { a = 7 ; *b = a ; b = &a ; *b = 4 ; printf("%d, %dn", a, *b) ; } int main() { int m = 3, n = 5; F(m, &n) ; printf("%d, %dn", m, n) ; return 0; } 4, 4 3, 7
  • 19. 1/14/10 Pointers to struct /* define a struct for related student data */ typedef struct student { char name[50]; char major [20]; double gpa; } STUDENT; STUDENT bob = {"Bob Smith", "Math", 3.77}; STUDENT sally = {"Sally", "CSEE", 4.0}; STUDENT *pStudent; /* pStudent is a "pointer to struct student" */ /* make pStudent point to bob */ pStudent = &bob; /* use -> to access the members */ printf ("Bob's name: %sn", pStudent->name); printf ("Bob's gpa : %fn", pStudent->gpa); /* make pStudent point to sally */ pStudent = &sally; printf ("Sally's name: %sn", pStudent->name); printf ("Sally's gpa: %fn", pStudent->gpa); Note too that the following are equivalent. Why?? pStudent->gpa and (*pStudent).gpa /* the parentheses are necessary */
  • 20. 9/24/10 Pointer to struct for functions void PrintStudent(STUDENT *studentp) { printf(“Name : %sn”, studentp->name); printf(“Major: %sn”, studentp->major); printf(“GPA : %4.2f”, studentp->gpa); } Passing a pointer to a struct to a function is more efficient than passing the struct itself. Why is this true?

Editor's Notes

  1. Trace the execution of swap to show that this doesn’t work
  2. Trace the execution of swap showing how/where variables are changed