SlideShare a Scribd company logo
Programming in C
Pointer Basics
What is a pointer
• In a generic sense, a “pointer” is anything that
tells us where something can be found.
– Addresses in the phone book
– URLs for webpages
– Road signs
1/14/10
What is a pointer ?
• In C, a pointer variable (or just “pointer”) is
similar 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 a
compact way
• They facilitate sharing between different parts of programs
• They make it possible to get new memory dynamically as
your program is running
• They make it easy to represent relationships among data
items.
1/14/10
Pointer Caution
• They are a powerful low-level device.
• Undisciplined use can be confusing and thus the
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 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 pointer
type *nameOfPointer;
1/14/10
Pointer Declaration
The declaration
int *intPtr;
defines the variable intPtr to be a pointer to a variable of
type int. intPtr will contain the memory address of some
int variable or int array. 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 the
same 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 are
* (star) and & (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 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 ( & ) to obtain the address of the pointee
• Use star ( * ) to get / change the value of the pointee
• Use %p to print the value of a pointer with printf( )
• 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 pointer
• NULL indicates that this pointer does not point to any
variable (there is no pointee)
• Often used when pointers are declared
int *pInt = NULL;
• Often used as the return type of functions that return a
pointer to indicate function failure
int *myPtr;
myPtr = myFunction( );
if (myPtr == NULL){
/* something bad happened */
}
• Dereferencing a pointer whose value is NULL will result in
program termination.
1/14/10
Pointers and Function Arguments
• Since C passes all primitive function arguments “by value”
there is no direct way for a function to alter a variable in the
calling code.
• This version of the swap function doesn’t work. 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 to
the values to be exchanged.
• 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 function
can be used to have a function “return” multiple
values.
• The pointer arguments point to variables in the
calling code which are changed (“returned”) by
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?
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

Pointers in C
Pointers in CPointers in C
Pointers in C
Prabhu Govind
 
Pointers in c - Mohammad Salman
Pointers in c - Mohammad SalmanPointers in c - Mohammad Salman
Pointers in c - Mohammad Salman
MohammadSalman129
 
Data Structure and Algorithms Linked List
Data Structure and Algorithms Linked ListData Structure and Algorithms Linked List
Data Structure and Algorithms Linked List
ManishPrajapati78
 
C programming - Pointers
C programming - PointersC programming - Pointers
C programming - Pointers
Wingston
 
pointers
pointerspointers
pointers
teach4uin
 
detailed information about Pointers in c language
detailed information about Pointers in c languagedetailed information about Pointers in c language
detailed information about Pointers in c language
gourav kottawar
 
Pointers & References in C++
Pointers & References in C++Pointers & References in C++
Pointers & References in C++
Ilio Catallo
 
C++ references
C++ referencesC++ references
C++ references
corehard_by
 
Pointers in c
Pointers in cPointers in c
Pointers in cMohd Arif
 
Pointers in C
Pointers in CPointers in C
Pointers in C
Monishkanungo
 
Pointers (Pp Tminimizer)
Pointers (Pp Tminimizer)Pointers (Pp Tminimizer)
Pointers (Pp Tminimizer)tech4us
 
Pointer in c
Pointer in cPointer in c
Pointer in c
Imamul Kadir
 
Pointer in C
Pointer in CPointer in C
Pointer in C
Sonya Akter Rupa
 
CPU : Structures And Unions
CPU : Structures And UnionsCPU : Structures And Unions
CPU : Structures And Unions
Dhrumil Patel
 
Pointers in C/C++ Programming
Pointers in C/C++ ProgrammingPointers in C/C++ Programming
Pointers in C/C++ Programming
Faisal Shahzad Khan
 
Presentation on pointer.
Presentation on pointer.Presentation on pointer.
Presentation on pointer.
Md. Afif Al Mamun
 
ppt on pointers
ppt on pointersppt on pointers
ppt on pointers
Riddhi Patel
 
C pointers
C pointersC pointers
C pointers
Aravind Mohan
 
Void pointer in c
Void pointer in cVoid pointer in c
Void pointer in c
SANDIP MORADIYA
 

What's hot (20)

Pointers in C
Pointers in CPointers in C
Pointers in C
 
Pointers in c - Mohammad Salman
Pointers in c - Mohammad SalmanPointers in c - Mohammad Salman
Pointers in c - Mohammad Salman
 
Ponters
PontersPonters
Ponters
 
Data Structure and Algorithms Linked List
Data Structure and Algorithms Linked ListData Structure and Algorithms Linked List
Data Structure and Algorithms Linked List
 
C programming - Pointers
C programming - PointersC programming - Pointers
C programming - Pointers
 
pointers
pointerspointers
pointers
 
detailed information about Pointers in c language
detailed information about Pointers in c languagedetailed information about Pointers in c language
detailed information about Pointers in c language
 
Pointers & References in C++
Pointers & References in C++Pointers & References in C++
Pointers & References in C++
 
C++ references
C++ referencesC++ references
C++ references
 
Pointers in c
Pointers in cPointers in c
Pointers in c
 
Pointers in C
Pointers in CPointers in C
Pointers in C
 
Pointers (Pp Tminimizer)
Pointers (Pp Tminimizer)Pointers (Pp Tminimizer)
Pointers (Pp Tminimizer)
 
Pointer in c
Pointer in cPointer in c
Pointer in c
 
Pointer in C
Pointer in CPointer in C
Pointer in C
 
CPU : Structures And Unions
CPU : Structures And UnionsCPU : Structures And Unions
CPU : Structures And Unions
 
Pointers in C/C++ Programming
Pointers in C/C++ ProgrammingPointers in C/C++ Programming
Pointers in C/C++ Programming
 
Presentation on pointer.
Presentation on pointer.Presentation on pointer.
Presentation on pointer.
 
ppt on pointers
ppt on pointersppt on pointers
ppt on pointers
 
C pointers
C pointersC pointers
C pointers
 
Void pointer in c
Void pointer in cVoid pointer in c
Void pointer in c
 

Viewers also liked

C pointer
C pointerC pointer
Pointers in C Programming
Pointers in C ProgrammingPointers in C Programming
Pointers in C Programming
Jasleen Kaur (Chandigarh University)
 
C++ Pointers
C++ PointersC++ Pointers
C++ Pointers
Chaand Sheikh
 
Unit 6 pointers
Unit 6   pointersUnit 6   pointers
Unit 6 pointers
George Erfesoglou
 
Pointers - DataStructures
Pointers - DataStructuresPointers - DataStructures
Pointers - DataStructures
Omair Imtiaz Ansari
 
Pointers
PointersPointers
Pointers
sarith divakar
 
Pointers in c++
Pointers in c++Pointers in c++
Pointers in c++
Vineeta Garg
 
Agricultural Conversion Study Example
Agricultural Conversion Study ExampleAgricultural Conversion Study Example
Agricultural Conversion Study ExampleCEQAplanner
 
Prospects from AMPLIFIRE
Prospects from AMPLIFIREProspects from AMPLIFIRE
Intro To C++ - Class 06 - Introduction To Classes, Objects, & Strings, Part II
Intro To C++ - Class 06 - Introduction To Classes, Objects, & Strings, Part IIIntro To C++ - Class 06 - Introduction To Classes, Objects, & Strings, Part II
Intro To C++ - Class 06 - Introduction To Classes, Objects, & Strings, Part II
Blue Elephant Consulting
 
Travel management
Travel managementTravel management
Travel management1Parimal2
 
Pratik Bakane C++
Pratik Bakane C++Pratik Bakane C++
Pratik Bakane C++
pratikbakane
 
Pointers C programming
Pointers  C programmingPointers  C programming
Pointers C programming
Appili Vamsi Krishna
 
[C언어의정석] ch7 포인터(pointer)
[C언어의정석] ch7 포인터(pointer)[C언어의정석] ch7 포인터(pointer)
[C언어의정석] ch7 포인터(pointer)
성 남궁
 
Lecture 8 Library classes
Lecture 8 Library classesLecture 8 Library classes
Lecture 8 Library classes
Syed Afaq Shah MACS CP
 
Lecture 2 C++ | Variable Scope, Operators in c++
Lecture 2 C++ | Variable Scope, Operators in c++Lecture 2 C++ | Variable Scope, Operators in c++
Lecture 2 C++ | Variable Scope, Operators in c++
Himanshu Kaushik
 

Viewers also liked (20)

Pointers in C
Pointers in CPointers in C
Pointers in C
 
C pointer
C pointerC pointer
C pointer
 
Pointers in C Programming
Pointers in C ProgrammingPointers in C Programming
Pointers in C Programming
 
C++ Pointers
C++ PointersC++ Pointers
C++ Pointers
 
Unit 6 pointers
Unit 6   pointersUnit 6   pointers
Unit 6 pointers
 
CSE240 Pointers
CSE240 PointersCSE240 Pointers
CSE240 Pointers
 
Pointers - DataStructures
Pointers - DataStructuresPointers - DataStructures
Pointers - DataStructures
 
Pointers
PointersPointers
Pointers
 
Pointers in c++
Pointers in c++Pointers in c++
Pointers in c++
 
Agricultural Conversion Study Example
Agricultural Conversion Study ExampleAgricultural Conversion Study Example
Agricultural Conversion Study Example
 
Prospects from AMPLIFIRE
Prospects from AMPLIFIREProspects from AMPLIFIRE
Prospects from AMPLIFIRE
 
Intro To C++ - Class 06 - Introduction To Classes, Objects, & Strings, Part II
Intro To C++ - Class 06 - Introduction To Classes, Objects, & Strings, Part IIIntro To C++ - Class 06 - Introduction To Classes, Objects, & Strings, Part II
Intro To C++ - Class 06 - Introduction To Classes, Objects, & Strings, Part II
 
Travel management
Travel managementTravel management
Travel management
 
Pointers+(2)
Pointers+(2)Pointers+(2)
Pointers+(2)
 
Pratik Bakane C++
Pratik Bakane C++Pratik Bakane C++
Pratik Bakane C++
 
Pointers C programming
Pointers  C programmingPointers  C programming
Pointers C programming
 
[C언어의정석] ch7 포인터(pointer)
[C언어의정석] ch7 포인터(pointer)[C언어의정석] ch7 포인터(pointer)
[C언어의정석] ch7 포인터(pointer)
 
Lecture 8 Library classes
Lecture 8 Library classesLecture 8 Library classes
Lecture 8 Library classes
 
Carnot engine
Carnot engineCarnot engine
Carnot engine
 
Lecture 2 C++ | Variable Scope, Operators in c++
Lecture 2 C++ | Variable Scope, Operators in c++Lecture 2 C++ | Variable Scope, Operators in c++
Lecture 2 C++ | Variable Scope, Operators in c++
 

Similar to C pointer basics

btech-1picu-5pointerstructureunionandintrotofilehandling-150122010700-conver.ppt
btech-1picu-5pointerstructureunionandintrotofilehandling-150122010700-conver.pptbtech-1picu-5pointerstructureunionandintrotofilehandling-150122010700-conver.ppt
btech-1picu-5pointerstructureunionandintrotofilehandling-150122010700-conver.ppt
chintuyadav19
 
Lap trinh C co ban va nang cao
Lap trinh C co ban va nang caoLap trinh C co ban va nang cao
Lap trinh C co ban va nang cao
VietJackTeam
 
Diploma ii cfpc- u-5.1 pointer, structure ,union and intro to file handling
Diploma ii  cfpc- u-5.1 pointer, structure ,union and intro to file handlingDiploma ii  cfpc- u-5.1 pointer, structure ,union and intro to file handling
Diploma ii cfpc- u-5.1 pointer, structure ,union and intro to file handling
Rai University
 
pointer, structure ,union and intro to file handling
pointer, structure ,union and intro to file handlingpointer, structure ,union and intro to file handling
pointer, structure ,union and intro to file handling
Rai University
 
Btech 1 pic u-5 pointer, structure ,union and intro to file handling
Btech 1 pic u-5 pointer, structure ,union and intro to file handlingBtech 1 pic u-5 pointer, structure ,union and intro to file handling
Btech 1 pic u-5 pointer, structure ,union and intro to file handling
Rai University
 
Mca 1 pic u-5 pointer, structure ,union and intro to file handling
Mca 1 pic u-5 pointer, structure ,union and intro to file handlingMca 1 pic u-5 pointer, structure ,union and intro to file handling
Mca 1 pic u-5 pointer, structure ,union and intro to file handling
Rai University
 
pointer, structure ,union and intro to file handling
pointer, structure ,union and intro to file handlingpointer, structure ,union and intro to file handling
pointer, structure ,union and intro to file handling
Rai University
 
Bsc cs 1 pic u-5 pointer, structure ,union and intro to file handling
Bsc cs 1 pic u-5 pointer, structure ,union and intro to file handlingBsc cs 1 pic u-5 pointer, structure ,union and intro to file handling
Bsc cs 1 pic u-5 pointer, structure ,union and intro to file handling
Rai University
 
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
sumitbardhan
 
Pointers-Computer programming
Pointers-Computer programmingPointers-Computer programming
Pointers-Computer programming
nmahi96
 
VIT351 Software Development VI Unit3
VIT351 Software Development VI Unit3VIT351 Software Development VI Unit3
VIT351 Software Development VI Unit3
YOGESH SINGH
 
PSPC--UNIT-5.pdf
PSPC--UNIT-5.pdfPSPC--UNIT-5.pdf
PSPC--UNIT-5.pdf
ArshiniGubbala3
 
Advanced C programming
Advanced C programmingAdvanced C programming
Advanced C programming
Claus Wu
 
pointers.pptx
pointers.pptxpointers.pptx
pointers.pptx
s170883BesiVyshnavi
 
Lk module5 pointers
Lk module5 pointersLk module5 pointers
Lk module5 pointers
Krishna Nanda
 
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
Ananthi Palanisamy
 
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
sudhakargeruganti
 
COM1407: Working with Pointers
COM1407: Working with PointersCOM1407: Working with Pointers
COM1407: Working with Pointers
Hemantha Kulathilake
 
ch08.ppt
ch08.pptch08.ppt
ch08.ppt
NewsMogul
 

Similar to C pointer basics (20)

btech-1picu-5pointerstructureunionandintrotofilehandling-150122010700-conver.ppt
btech-1picu-5pointerstructureunionandintrotofilehandling-150122010700-conver.pptbtech-1picu-5pointerstructureunionandintrotofilehandling-150122010700-conver.ppt
btech-1picu-5pointerstructureunionandintrotofilehandling-150122010700-conver.ppt
 
Lap trinh C co ban va nang cao
Lap trinh C co ban va nang caoLap trinh C co ban va nang cao
Lap trinh C co ban va nang cao
 
Diploma ii cfpc- u-5.1 pointer, structure ,union and intro to file handling
Diploma ii  cfpc- u-5.1 pointer, structure ,union and intro to file handlingDiploma ii  cfpc- u-5.1 pointer, structure ,union and intro to file handling
Diploma ii cfpc- u-5.1 pointer, structure ,union and intro to file handling
 
pointer, structure ,union and intro to file handling
pointer, structure ,union and intro to file handlingpointer, structure ,union and intro to file handling
pointer, structure ,union and intro to file handling
 
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
 
Mca 1 pic u-5 pointer, structure ,union and intro to file handling
Mca 1 pic u-5 pointer, structure ,union and intro to file handlingMca 1 pic u-5 pointer, structure ,union and intro to file handling
Mca 1 pic u-5 pointer, structure ,union and intro to file handling
 
pointer, structure ,union and intro to file handling
pointer, structure ,union and intro to file handlingpointer, structure ,union and intro to file handling
pointer, structure ,union and intro to file handling
 
Bsc cs 1 pic u-5 pointer, structure ,union and intro to file handling
Bsc cs 1 pic u-5 pointer, structure ,union and intro to file handlingBsc cs 1 pic u-5 pointer, structure ,union and intro to file handling
Bsc cs 1 pic u-5 pointer, structure ,union and intro to file handling
 
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
 
VIT351 Software Development VI Unit3
VIT351 Software Development VI Unit3VIT351 Software Development VI Unit3
VIT351 Software Development VI Unit3
 
PSPC--UNIT-5.pdf
PSPC--UNIT-5.pdfPSPC--UNIT-5.pdf
PSPC--UNIT-5.pdf
 
Advanced C programming
Advanced C programmingAdvanced C programming
Advanced C programming
 
pointers.pptx
pointers.pptxpointers.pptx
pointers.pptx
 
Advanced pointers
Advanced pointersAdvanced pointers
Advanced pointers
 
Lk module5 pointers
Lk module5 pointersLk module5 pointers
Lk module5 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
 
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
 
COM1407: Working with Pointers
COM1407: Working with PointersCOM1407: Working with Pointers
COM1407: Working with Pointers
 
ch08.ppt
ch08.pptch08.ppt
ch08.ppt
 

Recently uploaded

Enhancing Research Orchestration Capabilities at ORNL.pdf
Enhancing Research Orchestration Capabilities at ORNL.pdfEnhancing Research Orchestration Capabilities at ORNL.pdf
Enhancing Research Orchestration Capabilities at ORNL.pdf
Globus
 
Cyaniclab : Software Development Agency Portfolio.pdf
Cyaniclab : Software Development Agency Portfolio.pdfCyaniclab : Software Development Agency Portfolio.pdf
Cyaniclab : Software Development Agency Portfolio.pdf
Cyanic lab
 
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERRORTROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
Tier1 app
 
Dominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdf
Dominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdfDominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdf
Dominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdf
AMB-Review
 
How Recreation Management Software Can Streamline Your Operations.pptx
How Recreation Management Software Can Streamline Your Operations.pptxHow Recreation Management Software Can Streamline Your Operations.pptx
How Recreation Management Software Can Streamline Your Operations.pptx
wottaspaceseo
 
2024 RoOUG Security model for the cloud.pptx
2024 RoOUG Security model for the cloud.pptx2024 RoOUG Security model for the cloud.pptx
2024 RoOUG Security model for the cloud.pptx
Georgi Kodinov
 
De mooiste recreatieve routes ontdekken met RouteYou en FME
De mooiste recreatieve routes ontdekken met RouteYou en FMEDe mooiste recreatieve routes ontdekken met RouteYou en FME
De mooiste recreatieve routes ontdekken met RouteYou en FME
Jelle | Nordend
 
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
informapgpstrackings
 
Understanding Globus Data Transfers with NetSage
Understanding Globus Data Transfers with NetSageUnderstanding Globus Data Transfers with NetSage
Understanding Globus Data Transfers with NetSage
Globus
 
Globus Compute Introduction - GlobusWorld 2024
Globus Compute Introduction - GlobusWorld 2024Globus Compute Introduction - GlobusWorld 2024
Globus Compute Introduction - GlobusWorld 2024
Globus
 
How to Position Your Globus Data Portal for Success Ten Good Practices
How to Position Your Globus Data Portal for Success Ten Good PracticesHow to Position Your Globus Data Portal for Success Ten Good Practices
How to Position Your Globus Data Portal for Success Ten Good Practices
Globus
 
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Shahin Sheidaei
 
Providing Globus Services to Users of JASMIN for Environmental Data Analysis
Providing Globus Services to Users of JASMIN for Environmental Data AnalysisProviding Globus Services to Users of JASMIN for Environmental Data Analysis
Providing Globus Services to Users of JASMIN for Environmental Data Analysis
Globus
 
Vitthal Shirke Microservices Resume Montevideo
Vitthal Shirke Microservices Resume MontevideoVitthal Shirke Microservices Resume Montevideo
Vitthal Shirke Microservices Resume Montevideo
Vitthal Shirke
 
How Does XfilesPro Ensure Security While Sharing Documents in Salesforce?
How Does XfilesPro Ensure Security While Sharing Documents in Salesforce?How Does XfilesPro Ensure Security While Sharing Documents in Salesforce?
How Does XfilesPro Ensure Security While Sharing Documents in Salesforce?
XfilesPro
 
First Steps with Globus Compute Multi-User Endpoints
First Steps with Globus Compute Multi-User EndpointsFirst Steps with Globus Compute Multi-User Endpoints
First Steps with Globus Compute Multi-User Endpoints
Globus
 
Lecture 1 Introduction to games development
Lecture 1 Introduction to games developmentLecture 1 Introduction to games development
Lecture 1 Introduction to games development
abdulrafaychaudhry
 
Explore Modern SharePoint Templates for 2024
Explore Modern SharePoint Templates for 2024Explore Modern SharePoint Templates for 2024
Explore Modern SharePoint Templates for 2024
Sharepoint Designs
 
Prosigns: Transforming Business with Tailored Technology Solutions
Prosigns: Transforming Business with Tailored Technology SolutionsProsigns: Transforming Business with Tailored Technology Solutions
Prosigns: Transforming Business with Tailored Technology Solutions
Prosigns
 
Globus Compute wth IRI Workflows - GlobusWorld 2024
Globus Compute wth IRI Workflows - GlobusWorld 2024Globus Compute wth IRI Workflows - GlobusWorld 2024
Globus Compute wth IRI Workflows - GlobusWorld 2024
Globus
 

Recently uploaded (20)

Enhancing Research Orchestration Capabilities at ORNL.pdf
Enhancing Research Orchestration Capabilities at ORNL.pdfEnhancing Research Orchestration Capabilities at ORNL.pdf
Enhancing Research Orchestration Capabilities at ORNL.pdf
 
Cyaniclab : Software Development Agency Portfolio.pdf
Cyaniclab : Software Development Agency Portfolio.pdfCyaniclab : Software Development Agency Portfolio.pdf
Cyaniclab : Software Development Agency Portfolio.pdf
 
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERRORTROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
 
Dominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdf
Dominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdfDominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdf
Dominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdf
 
How Recreation Management Software Can Streamline Your Operations.pptx
How Recreation Management Software Can Streamline Your Operations.pptxHow Recreation Management Software Can Streamline Your Operations.pptx
How Recreation Management Software Can Streamline Your Operations.pptx
 
2024 RoOUG Security model for the cloud.pptx
2024 RoOUG Security model for the cloud.pptx2024 RoOUG Security model for the cloud.pptx
2024 RoOUG Security model for the cloud.pptx
 
De mooiste recreatieve routes ontdekken met RouteYou en FME
De mooiste recreatieve routes ontdekken met RouteYou en FMEDe mooiste recreatieve routes ontdekken met RouteYou en FME
De mooiste recreatieve routes ontdekken met RouteYou en FME
 
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
 
Understanding Globus Data Transfers with NetSage
Understanding Globus Data Transfers with NetSageUnderstanding Globus Data Transfers with NetSage
Understanding Globus Data Transfers with NetSage
 
Globus Compute Introduction - GlobusWorld 2024
Globus Compute Introduction - GlobusWorld 2024Globus Compute Introduction - GlobusWorld 2024
Globus Compute Introduction - GlobusWorld 2024
 
How to Position Your Globus Data Portal for Success Ten Good Practices
How to Position Your Globus Data Portal for Success Ten Good PracticesHow to Position Your Globus Data Portal for Success Ten Good Practices
How to Position Your Globus Data Portal for Success Ten Good Practices
 
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
 
Providing Globus Services to Users of JASMIN for Environmental Data Analysis
Providing Globus Services to Users of JASMIN for Environmental Data AnalysisProviding Globus Services to Users of JASMIN for Environmental Data Analysis
Providing Globus Services to Users of JASMIN for Environmental Data Analysis
 
Vitthal Shirke Microservices Resume Montevideo
Vitthal Shirke Microservices Resume MontevideoVitthal Shirke Microservices Resume Montevideo
Vitthal Shirke Microservices Resume Montevideo
 
How Does XfilesPro Ensure Security While Sharing Documents in Salesforce?
How Does XfilesPro Ensure Security While Sharing Documents in Salesforce?How Does XfilesPro Ensure Security While Sharing Documents in Salesforce?
How Does XfilesPro Ensure Security While Sharing Documents in Salesforce?
 
First Steps with Globus Compute Multi-User Endpoints
First Steps with Globus Compute Multi-User EndpointsFirst Steps with Globus Compute Multi-User Endpoints
First Steps with Globus Compute Multi-User Endpoints
 
Lecture 1 Introduction to games development
Lecture 1 Introduction to games developmentLecture 1 Introduction to games development
Lecture 1 Introduction to games development
 
Explore Modern SharePoint Templates for 2024
Explore Modern SharePoint Templates for 2024Explore Modern SharePoint Templates for 2024
Explore Modern SharePoint Templates for 2024
 
Prosigns: Transforming Business with Tailored Technology Solutions
Prosigns: Transforming Business with Tailored Technology SolutionsProsigns: Transforming Business with Tailored Technology Solutions
Prosigns: Transforming Business with Tailored Technology Solutions
 
Globus Compute wth IRI Workflows - GlobusWorld 2024
Globus Compute wth IRI Workflows - GlobusWorld 2024Globus Compute wth IRI Workflows - GlobusWorld 2024
Globus Compute wth IRI Workflows - GlobusWorld 2024
 

C pointer basics

  • 2. What is a pointer • In a generic sense, a “pointer” is anything that tells us where something can be found. – Addresses in the phone book – URLs for webpages – Road signs
  • 3. 1/14/10 What is a pointer ? • In C, a pointer variable (or just “pointer”) is similar 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
  • 4. 1/14/10 Why Pointers? • They allow you to refer to large data structures in a compact way • They facilitate sharing between different parts of programs • They make it possible to get new memory dynamically as your program is running • They make it easy to represent relationships among data items.
  • 5. 1/14/10 Pointer Caution • They are a powerful low-level device. • Undisciplined use can be confusing and thus the source of subtle, hard-to-find bugs. – Program crashes – Memory leaks – Unpredictable results
  • 6. 1/14/10 C Pointer Variables To 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 pointer type *nameOfPointer;
  • 7. 1/14/10 Pointer Declaration The declaration int *intPtr; defines the variable intPtr to be a pointer to a variable of type int. intPtr will contain the memory address of some int variable or int array. 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 the same line. In this definition int *intPtr, intPtr2; intPtr is a pointer to an int, but intPtr2 is not!
  • 8. 1/14/10 Pointer Operators The two primary operators used with pointers are * (star) and & (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( )
  • 9. 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.)
  • 10. 1/14/10 Pointer and Variable types • The 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 */
  • 11. 1/14/10 More Pointer Code • Use ampersand ( & ) to obtain the address of the pointee • Use star ( * ) to get / change the value of the pointee • Use %p to print the value of a pointer with printf( ) • 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) ;
  • 12. 1/14/10 NULL • NULL is a special value which may be assigned to a pointer • NULL indicates that this pointer does not point to any variable (there is no pointee) • Often used when pointers are declared int *pInt = NULL; • Often used as the return type of functions that return a pointer to indicate function failure int *myPtr; myPtr = myFunction( ); if (myPtr == NULL){ /* something bad happened */ } • Dereferencing a pointer whose value is NULL will result in program termination.
  • 13. 1/14/10 Pointers and Function Arguments • Since C passes all primitive function arguments “by value” there is no direct way for a function to alter a variable in the calling code. • This version of the swap function doesn’t work. 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; }
  • 14. 1/14/10 A better swap( ) • The desired effect can be obtained by passing pointers to the values to be exchanged. • 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; }
  • 15. 1/14/10 More Pointer Function Parameters • Passing the address of variable(s) to a function can be used to have a function “return” multiple values. • The pointer arguments point to variables in the calling code which are changed (“returned”) by the function.
  • 16. 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; }
  • 17. 1/14/10 An Exercise • 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
  • 18. 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 */
  • 19. 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?