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 (20)

C data types, arrays and structs
C data types, arrays and structsC data types, arrays and structs
C data types, arrays and structs
Saad Sheikh
 
Pointers in c++
Pointers in c++Pointers in c++
Pointers in c++
Vineeta Garg
 
Dynamic memory allocation in c++
Dynamic memory allocation in c++Dynamic memory allocation in c++
Dynamic memory allocation in c++
Tech_MX
 
Variables in python
Variables in pythonVariables in python
Variables in python
Jaya Kumari
 
Pointers in c - Mohammad Salman
Pointers in c - Mohammad SalmanPointers in c - Mohammad Salman
Pointers in c - Mohammad Salman
MohammadSalman129
 
C pointer
C pointerC pointer
C pointer
University of Potsdam
 
Pointer in C
Pointer in CPointer in C
Pointer in C
bipchulabmki
 
Pointers C programming
Pointers  C programmingPointers  C programming
Pointers C programming
Appili Vamsi Krishna
 
Function overloading(c++)
Function overloading(c++)Function overloading(c++)
Function overloading(c++)
Ritika Sharma
 
Intro to c++
Intro to c++Intro to c++
Intro to c++
temkin abdlkader
 
Pointers in C
Pointers in CPointers in C
Pointers in C
Monishkanungo
 
pointers.pptx
pointers.pptxpointers.pptx
pointers.pptx
janithlakshan1
 
Binary Tree Traversal
Binary Tree TraversalBinary Tree Traversal
Binary Tree Traversal
Dhrumil Panchal
 
Python Control structures
Python Control structuresPython Control structures
Python Control structures
Siddique Ibrahim
 
Data types in C language
Data types in C languageData types in C language
Data types in C language
kashyap399
 
Insertion in singly linked list
Insertion in singly linked listInsertion in singly linked list
Insertion in singly linked list
Keval Bhogayata
 
Control Structures
Control StructuresControl Structures
Control Structures
Ghaffar Khan
 
15 bitwise operators
15 bitwise operators15 bitwise operators
15 bitwise operators
Ravindra Rathore
 
Numeric Data types in Python
Numeric Data types in PythonNumeric Data types in Python
Numeric Data types in Python
jyostna bodapati
 
Call by value or call by reference in C++
Call by value or call by reference in C++Call by value or call by reference in C++
Call by value or call by reference in C++
Sachin Yadav
 
C data types, arrays and structs
C data types, arrays and structsC data types, arrays and structs
C data types, arrays and structs
Saad Sheikh
 
Dynamic memory allocation in c++
Dynamic memory allocation in c++Dynamic memory allocation in c++
Dynamic memory allocation in c++
Tech_MX
 
Variables in python
Variables in pythonVariables in python
Variables in python
Jaya Kumari
 
Pointers in c - Mohammad Salman
Pointers in c - Mohammad SalmanPointers in c - Mohammad Salman
Pointers in c - Mohammad Salman
MohammadSalman129
 
Function overloading(c++)
Function overloading(c++)Function overloading(c++)
Function overloading(c++)
Ritika Sharma
 
Data types in C language
Data types in C languageData types in C language
Data types in C language
kashyap399
 
Insertion in singly linked list
Insertion in singly linked listInsertion in singly linked list
Insertion in singly linked list
Keval Bhogayata
 
Control Structures
Control StructuresControl Structures
Control Structures
Ghaffar Khan
 
Numeric Data types in Python
Numeric Data types in PythonNumeric Data types in Python
Numeric Data types in Python
jyostna bodapati
 
Call by value or call by reference in C++
Call by value or call by reference in C++Call by value or call by reference in C++
Call by value or call by reference in C++
Sachin Yadav
 

Viewers also liked (20)

Pointers in C
Pointers in CPointers in C
Pointers in C
guestdc3f16
 
C++ Pointers
C++ PointersC++ Pointers
C++ Pointers
Chaand Sheikh
 
Unit 6 pointers
Unit 6   pointersUnit 6   pointers
Unit 6 pointers
George Erfesoglou
 
C Pointers
C PointersC Pointers
C Pointers
omukhtar
 
CSE240 Pointers
CSE240 PointersCSE240 Pointers
CSE240 Pointers
Garrett Gutierrez
 
Pointers - DataStructures
Pointers - DataStructuresPointers - DataStructures
Pointers - DataStructures
Omair Imtiaz Ansari
 
C programming - Pointers
C programming - PointersC programming - Pointers
C programming - Pointers
Wingston
 
Ponters
PontersPonters
Ponters
Mukund Trivedi
 
Pointers
PointersPointers
Pointers
sarith divakar
 
Agricultural Conversion Study Example
Agricultural Conversion Study ExampleAgricultural Conversion Study Example
Agricultural Conversion Study Example
CEQAplanner
 
Prospects from AMPLIFIRE
Prospects from AMPLIFIREProspects from AMPLIFIRE
Prospects from AMPLIFIRE
Future Internet Research and Experimentation - FIRE
 
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 management
1Parimal2
 
Pointers+(2)
Pointers+(2)Pointers+(2)
Pointers+(2)
Rubal Bansal
 
Pratik Bakane C++
Pratik Bakane C++Pratik Bakane C++
Pratik Bakane C++
pratikbakane
 
[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
 
Pointers & References in C++
Pointers & References in C++Pointers & References in C++
Pointers & References in C++
Ilio Catallo
 
Carnot engine
Carnot engineCarnot engine
Carnot engine
Self-employed
 
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
 
Ad

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
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
 
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
 
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
 
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
 
2-Concept of Pointers in c programming.pptx
2-Concept of Pointers in c programming.pptx2-Concept of Pointers in c programming.pptx
2-Concept of Pointers in c programming.pptx
naushigrdcs
 
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
 
Advanced pointers
Advanced pointersAdvanced pointers
Advanced pointers
Koganti Ravikumar
 
Structured programming Unit-6-Strings-Unit-8-Pointer.pptx
Structured programming Unit-6-Strings-Unit-8-Pointer.pptxStructured programming Unit-6-Strings-Unit-8-Pointer.pptx
Structured programming Unit-6-Strings-Unit-8-Pointer.pptx
SuryaBasnet1
 
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
 
UNIT 4 POINTERS.pptx pointers pptx for basic c language
UNIT 4 POINTERS.pptx pointers pptx for basic c languageUNIT 4 POINTERS.pptx pointers pptx for basic c language
UNIT 4 POINTERS.pptx pointers pptx for basic c language
wwwskrilikeyou
 
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
 
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
 
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
 
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
 
2-Concept of Pointers in c programming.pptx
2-Concept of Pointers in c programming.pptx2-Concept of Pointers in c programming.pptx
2-Concept of Pointers in c programming.pptx
naushigrdcs
 
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
 
Advanced C programming
Advanced C programmingAdvanced C programming
Advanced C programming
Claus Wu
 
Structured programming Unit-6-Strings-Unit-8-Pointer.pptx
Structured programming Unit-6-Strings-Unit-8-Pointer.pptxStructured programming Unit-6-Strings-Unit-8-Pointer.pptx
Structured programming Unit-6-Strings-Unit-8-Pointer.pptx
SuryaBasnet1
 
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
 
UNIT 4 POINTERS.pptx pointers pptx for basic c language
UNIT 4 POINTERS.pptx pointers pptx for basic c languageUNIT 4 POINTERS.pptx pointers pptx for basic c language
UNIT 4 POINTERS.pptx pointers pptx for basic c language
wwwskrilikeyou
 
Ad

Recently uploaded (20)

Revolutionize Your Insurance Workflow with Claims Management Software
Revolutionize Your Insurance Workflow with Claims Management SoftwareRevolutionize Your Insurance Workflow with Claims Management Software
Revolutionize Your Insurance Workflow with Claims Management Software
Insurance Tech Services
 
Marketo & Dynamics can be Most Excellent to Each Other – The Sequel
Marketo & Dynamics can be Most Excellent to Each Other – The SequelMarketo & Dynamics can be Most Excellent to Each Other – The Sequel
Marketo & Dynamics can be Most Excellent to Each Other – The Sequel
BradBedford3
 
COBOL Programming with VSCode - IBM Certificate
COBOL Programming with VSCode - IBM CertificateCOBOL Programming with VSCode - IBM Certificate
COBOL Programming with VSCode - IBM Certificate
VICTOR MAESTRE RAMIREZ
 
iOS Developer Resume 2025 | Pramod Kumar
iOS Developer Resume 2025 | Pramod KumariOS Developer Resume 2025 | Pramod Kumar
iOS Developer Resume 2025 | Pramod Kumar
Pramod Kumar
 
How AI Can Improve Media Quality Testing Across Platforms (1).pptx
How AI Can Improve Media Quality Testing Across Platforms (1).pptxHow AI Can Improve Media Quality Testing Across Platforms (1).pptx
How AI Can Improve Media Quality Testing Across Platforms (1).pptx
kalichargn70th171
 
How to Generate Financial Statements in QuickBooks Like a Pro (1).pdf
How to Generate Financial Statements in QuickBooks Like a Pro (1).pdfHow to Generate Financial Statements in QuickBooks Like a Pro (1).pdf
How to Generate Financial Statements in QuickBooks Like a Pro (1).pdf
QuickBooks Training
 
Why Indonesia’s $12.63B Alt-Lending Boom Needs Loan Servicing Automation & Re...
Why Indonesia’s $12.63B Alt-Lending Boom Needs Loan Servicing Automation & Re...Why Indonesia’s $12.63B Alt-Lending Boom Needs Loan Servicing Automation & Re...
Why Indonesia’s $12.63B Alt-Lending Boom Needs Loan Servicing Automation & Re...
Prachi Desai
 
Design by Contract - Building Robust Software with Contract-First Development
Design by Contract - Building Robust Software with Contract-First DevelopmentDesign by Contract - Building Robust Software with Contract-First Development
Design by Contract - Building Robust Software with Contract-First Development
Par-Tec S.p.A.
 
Automating Map Production With FME and Python
Automating Map Production With FME and PythonAutomating Map Production With FME and Python
Automating Map Production With FME and Python
Safe Software
 
Maintaining + Optimizing Database Health: Vendors, Orchestrations, Enrichment...
Maintaining + Optimizing Database Health: Vendors, Orchestrations, Enrichment...Maintaining + Optimizing Database Health: Vendors, Orchestrations, Enrichment...
Maintaining + Optimizing Database Health: Vendors, Orchestrations, Enrichment...
BradBedford3
 
Top 5 Task Management Software to Boost Productivity in 2025
Top 5 Task Management Software to Boost Productivity in 2025Top 5 Task Management Software to Boost Productivity in 2025
Top 5 Task Management Software to Boost Productivity in 2025
Orangescrum
 
Key AI Technologies Used by Indian Artificial Intelligence Companies
Key AI Technologies Used by Indian Artificial Intelligence CompaniesKey AI Technologies Used by Indian Artificial Intelligence Companies
Key AI Technologies Used by Indian Artificial Intelligence Companies
Mypcot Infotech
 
Agentic Techniques in Retrieval-Augmented Generation with Azure AI Search
Agentic Techniques in Retrieval-Augmented Generation with Azure AI SearchAgentic Techniques in Retrieval-Augmented Generation with Azure AI Search
Agentic Techniques in Retrieval-Augmented Generation with Azure AI Search
Maxim Salnikov
 
Essentials of Resource Planning in a Downturn
Essentials of Resource Planning in a DownturnEssentials of Resource Planning in a Downturn
Essentials of Resource Planning in a Downturn
OnePlan Solutions
 
Rebuilding Cadabra Studio: AI as Our Core Foundation
Rebuilding Cadabra Studio: AI as Our Core FoundationRebuilding Cadabra Studio: AI as Our Core Foundation
Rebuilding Cadabra Studio: AI as Our Core Foundation
Cadabra Studio
 
Build Smarter, Deliver Faster with Choreo - An AI Native Internal Developer P...
Build Smarter, Deliver Faster with Choreo - An AI Native Internal Developer P...Build Smarter, Deliver Faster with Choreo - An AI Native Internal Developer P...
Build Smarter, Deliver Faster with Choreo - An AI Native Internal Developer P...
WSO2
 
Providing Better Biodiversity Through Better Data
Providing Better Biodiversity Through Better DataProviding Better Biodiversity Through Better Data
Providing Better Biodiversity Through Better Data
Safe Software
 
Leveraging Foundation Models to Infer Intents
Leveraging Foundation Models to Infer IntentsLeveraging Foundation Models to Infer Intents
Leveraging Foundation Models to Infer Intents
Keheliya Gallaba
 
Neuralink Templateeeeeeeeeeeeeeeeeeeeeeeeee
Neuralink TemplateeeeeeeeeeeeeeeeeeeeeeeeeeNeuralink Templateeeeeeeeeeeeeeeeeeeeeeeeee
Neuralink Templateeeeeeeeeeeeeeeeeeeeeeeeee
alexandernoetzold
 
Agile Software Engineering Methodologies
Agile Software Engineering MethodologiesAgile Software Engineering Methodologies
Agile Software Engineering Methodologies
Gaurav Sharma
 
Revolutionize Your Insurance Workflow with Claims Management Software
Revolutionize Your Insurance Workflow with Claims Management SoftwareRevolutionize Your Insurance Workflow with Claims Management Software
Revolutionize Your Insurance Workflow with Claims Management Software
Insurance Tech Services
 
Marketo & Dynamics can be Most Excellent to Each Other – The Sequel
Marketo & Dynamics can be Most Excellent to Each Other – The SequelMarketo & Dynamics can be Most Excellent to Each Other – The Sequel
Marketo & Dynamics can be Most Excellent to Each Other – The Sequel
BradBedford3
 
COBOL Programming with VSCode - IBM Certificate
COBOL Programming with VSCode - IBM CertificateCOBOL Programming with VSCode - IBM Certificate
COBOL Programming with VSCode - IBM Certificate
VICTOR MAESTRE RAMIREZ
 
iOS Developer Resume 2025 | Pramod Kumar
iOS Developer Resume 2025 | Pramod KumariOS Developer Resume 2025 | Pramod Kumar
iOS Developer Resume 2025 | Pramod Kumar
Pramod Kumar
 
How AI Can Improve Media Quality Testing Across Platforms (1).pptx
How AI Can Improve Media Quality Testing Across Platforms (1).pptxHow AI Can Improve Media Quality Testing Across Platforms (1).pptx
How AI Can Improve Media Quality Testing Across Platforms (1).pptx
kalichargn70th171
 
How to Generate Financial Statements in QuickBooks Like a Pro (1).pdf
How to Generate Financial Statements in QuickBooks Like a Pro (1).pdfHow to Generate Financial Statements in QuickBooks Like a Pro (1).pdf
How to Generate Financial Statements in QuickBooks Like a Pro (1).pdf
QuickBooks Training
 
Why Indonesia’s $12.63B Alt-Lending Boom Needs Loan Servicing Automation & Re...
Why Indonesia’s $12.63B Alt-Lending Boom Needs Loan Servicing Automation & Re...Why Indonesia’s $12.63B Alt-Lending Boom Needs Loan Servicing Automation & Re...
Why Indonesia’s $12.63B Alt-Lending Boom Needs Loan Servicing Automation & Re...
Prachi Desai
 
Design by Contract - Building Robust Software with Contract-First Development
Design by Contract - Building Robust Software with Contract-First DevelopmentDesign by Contract - Building Robust Software with Contract-First Development
Design by Contract - Building Robust Software with Contract-First Development
Par-Tec S.p.A.
 
Automating Map Production With FME and Python
Automating Map Production With FME and PythonAutomating Map Production With FME and Python
Automating Map Production With FME and Python
Safe Software
 
Maintaining + Optimizing Database Health: Vendors, Orchestrations, Enrichment...
Maintaining + Optimizing Database Health: Vendors, Orchestrations, Enrichment...Maintaining + Optimizing Database Health: Vendors, Orchestrations, Enrichment...
Maintaining + Optimizing Database Health: Vendors, Orchestrations, Enrichment...
BradBedford3
 
Top 5 Task Management Software to Boost Productivity in 2025
Top 5 Task Management Software to Boost Productivity in 2025Top 5 Task Management Software to Boost Productivity in 2025
Top 5 Task Management Software to Boost Productivity in 2025
Orangescrum
 
Key AI Technologies Used by Indian Artificial Intelligence Companies
Key AI Technologies Used by Indian Artificial Intelligence CompaniesKey AI Technologies Used by Indian Artificial Intelligence Companies
Key AI Technologies Used by Indian Artificial Intelligence Companies
Mypcot Infotech
 
Agentic Techniques in Retrieval-Augmented Generation with Azure AI Search
Agentic Techniques in Retrieval-Augmented Generation with Azure AI SearchAgentic Techniques in Retrieval-Augmented Generation with Azure AI Search
Agentic Techniques in Retrieval-Augmented Generation with Azure AI Search
Maxim Salnikov
 
Essentials of Resource Planning in a Downturn
Essentials of Resource Planning in a DownturnEssentials of Resource Planning in a Downturn
Essentials of Resource Planning in a Downturn
OnePlan Solutions
 
Rebuilding Cadabra Studio: AI as Our Core Foundation
Rebuilding Cadabra Studio: AI as Our Core FoundationRebuilding Cadabra Studio: AI as Our Core Foundation
Rebuilding Cadabra Studio: AI as Our Core Foundation
Cadabra Studio
 
Build Smarter, Deliver Faster with Choreo - An AI Native Internal Developer P...
Build Smarter, Deliver Faster with Choreo - An AI Native Internal Developer P...Build Smarter, Deliver Faster with Choreo - An AI Native Internal Developer P...
Build Smarter, Deliver Faster with Choreo - An AI Native Internal Developer P...
WSO2
 
Providing Better Biodiversity Through Better Data
Providing Better Biodiversity Through Better DataProviding Better Biodiversity Through Better Data
Providing Better Biodiversity Through Better Data
Safe Software
 
Leveraging Foundation Models to Infer Intents
Leveraging Foundation Models to Infer IntentsLeveraging Foundation Models to Infer Intents
Leveraging Foundation Models to Infer Intents
Keheliya Gallaba
 
Neuralink Templateeeeeeeeeeeeeeeeeeeeeeeeee
Neuralink TemplateeeeeeeeeeeeeeeeeeeeeeeeeeNeuralink Templateeeeeeeeeeeeeeeeeeeeeeeeee
Neuralink Templateeeeeeeeeeeeeeeeeeeeeeeeee
alexandernoetzold
 
Agile Software Engineering Methodologies
Agile Software Engineering MethodologiesAgile Software Engineering Methodologies
Agile Software Engineering Methodologies
Gaurav Sharma
 

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?