SlideShare a Scribd company logo
Pointers in C




 Omar Mukhtar
Outline


    Review of concepts in previous lectures

    Introduction to pointers

    Pointers as function arguments

    Pointers and arrays

    Pointer arithmetic

    Pointer-to-pointer
Review and Background


    Basic data types
       −     Place-holders for numeric data
               
                   Integer numbers (int, short, long)
               
                   Real numbers (float, double)
               
                   Characters / symbols codes (char)

    Arrays
       −     A contiguous list of a particular data type

    Functions
       −     Give “name” to a particular piece of code
       −     Modularization & reuse of code
Pointers


    The most useful and tricky concept in C
    language
       −   Other high level languages abstract-out this
           concept

    The most powerful construct too
       −   Makes C very fast
       −   Direct interaction with hardware
       −   Solves very complicated programming
           problems
What are pointers?


    Just another kind of “placeholder” to hold
    “address” of memory location
        −   Address is also a number
        −   Itself resides on some memory location

       Memory Address      Value
            0x8004           ...
            0x8008                        variable A
                            129
            0x800C           ...
            0x8010         0x8008        address of A
            0x8014           ...
What are pointers?

    Declare variables a, b
        −   int a, b;

    Declare a pointer
        −   int* pa;

    Set value of a
        −   a = 10;

    Point pa to address of a
        −   pa = &a;

    Set value of a using pa
        −   *pa = 12; pa = &b;
Pointer Operators


    “address-of” operator: &
       −   Gets address of a variable

    De-referencing operator: *
       −   Accesses the memory location this pointer
           holds address of
Pointers and Functions


    A function can be passed arguments using
    basic data types
        −    int prod(int a, int b) { return
             a*b; }

    How to return multiple values from function?
        −    void prod_and_sum(int a, int b,
             int*p, int* s)
             { *p = a*b; *s = a+b; }
In & Out Arguments of Function


    A function may like to pass values and get the
    result in the same variables. e.g. a Swap
    function.

    void swap(int* a, int* b) { int c;
     c = *b; *b = *a; *a = c; }

    int a = 5; b = 6;

    swap(&a, &b);

    // a hold 6 and b hold 5 now.
Pointers and Arrays


    Since arrays are a contiguous set of variables
    in memory, we can access them with pointers

    int arr[5];

    int *p = &arr[0];

    *(p+0) = 1;      // arr[0]

    *(p+1) = 2;      // arr[1]

    *(p+2) = 4;      // arr[2]

    *(p+3) = 8;      // arr[3]

    ...
Pointer Arithmetic

    Arithmetic operators work as usual on ordinary
    data types.
        −   int a = 1; a++; // a == 2

    It gets a bit complicated when arithmetic
    operators are used on pointers

    int* p = 0x8004; p++;

    What does p hold now? 0x8005???

    Compiler knows that p is a pointer to integer
    type data, so an increment to it should point to
    next integer in memory. Hence 0x8008.
Pointer Arithmetic

    So an arithmetic operator increases or
    decreases its contents by the size of data type
    it points to

    int* pi = 0x8004; double* pd =
    0x9004; char* pc = 0xa004;

    pi++; // pi == 0x8008

    pd++; // pd == 0x900c

    pc++; // pc == 0xa005

    Only '+' and '-' operator are allowed. '*' and '/'
    are meaningless.
Pointer-to-Pointer

    Pointer variable is just a place-holder of an
    address value, and itself is a variable.
        −   Hence a pointer can hold address of other
            pointer variable. In that case it is called a
            “double pointer”.

    int*p; int **pp; pp = &p;

    e.g a function may like to return a pointer
    value

    void pp_example(int** p) { *p =
    0x8004; }

    int *p; pp_example(&p);
Pointer Pitfalls

    Since pointer holds address of memory
    location, it must never be used without proper
    initialization.

    An uninitialized pointer may hold address of
    some memory location that is protected by
    Operating System. In such case, de-
    referencing a pointer may crash the program.

    An initialized pointer does not know the
    memory location, it is pointing to is, holds a
    valid value or some garbage.

    A pointer cannot track boundaries of an array.

More Related Content

What's hot

Pointers in C Language
Pointers in C LanguagePointers in C Language
Pointers in C Language
madan reddy
 
Multidimensional array in C
Multidimensional array in CMultidimensional array in C
Multidimensional array in C
Smit Parikh
 
Pointers in c++
Pointers in c++Pointers in c++
Pointers in c++
Rajat Busheheri
 
Pointers
PointersPointers
Pointers
sarith divakar
 
Data Type in C Programming
Data Type in C ProgrammingData Type in C Programming
Data Type in C Programming
Qazi Shahzad Ali
 
pointers
pointerspointers
pointers
teach4uin
 
Array and string
Array and stringArray and string
Array and string
prashant chelani
 
Functions in C
Functions in CFunctions in C
Functions in C
Kamal Acharya
 
Constants in C Programming
Constants in C ProgrammingConstants in C Programming
Constants in C Programming
programming9
 
Pointers & References in C++
Pointers & References in C++Pointers & References in C++
Pointers & References in C++
Ilio Catallo
 
Array Of Pointers
Array Of PointersArray Of Pointers
Array Of Pointers
Sharad Dubey
 
C Programming Storage classes, Recursion
C Programming Storage classes, RecursionC Programming Storage classes, Recursion
C Programming Storage classes, Recursion
Sreedhar Chowdam
 
Presentation on pointer.
Presentation on pointer.Presentation on pointer.
Presentation on pointer.
Md. Afif Al Mamun
 
Strings Functions in C Programming
Strings Functions in C ProgrammingStrings Functions in C Programming
Strings Functions in C Programming
DevoAjit Gupta
 
Structure in c
Structure in cStructure in c
Structure in c
Prabhu Govind
 
C programming - Pointers
C programming - PointersC programming - Pointers
C programming - Pointers
Wingston
 
structure and union
structure and unionstructure and union
structure and unionstudent
 
Pointer in C
Pointer in CPointer in C
Pointer in C
bipchulabmki
 
C string
C stringC string

What's hot (20)

Pointers in C
Pointers in CPointers in C
Pointers in C
 
Pointers in C Language
Pointers in C LanguagePointers in C Language
Pointers in C Language
 
Multidimensional array in C
Multidimensional array in CMultidimensional array in C
Multidimensional array in C
 
Pointers in c++
Pointers in c++Pointers in c++
Pointers in c++
 
Pointers
PointersPointers
Pointers
 
Data Type in C Programming
Data Type in C ProgrammingData Type in C Programming
Data Type in C Programming
 
pointers
pointerspointers
pointers
 
Array and string
Array and stringArray and string
Array and string
 
Functions in C
Functions in CFunctions in C
Functions in C
 
Constants in C Programming
Constants in C ProgrammingConstants in C Programming
Constants in C Programming
 
Pointers & References in C++
Pointers & References in C++Pointers & References in C++
Pointers & References in C++
 
Array Of Pointers
Array Of PointersArray Of Pointers
Array Of Pointers
 
C Programming Storage classes, Recursion
C Programming Storage classes, RecursionC Programming Storage classes, Recursion
C Programming Storage classes, Recursion
 
Presentation on pointer.
Presentation on pointer.Presentation on pointer.
Presentation on pointer.
 
Strings Functions in C Programming
Strings Functions in C ProgrammingStrings Functions in C Programming
Strings Functions in C Programming
 
Structure in c
Structure in cStructure in c
Structure in c
 
C programming - Pointers
C programming - PointersC programming - Pointers
C programming - Pointers
 
structure and union
structure and unionstructure and union
structure and union
 
Pointer in C
Pointer in CPointer in C
Pointer in C
 
C string
C stringC string
C string
 

Similar to C Pointers

pointers.pptx
pointers.pptxpointers.pptx
pointers.pptx
janithlakshan1
 
PSPC--UNIT-5.pdf
PSPC--UNIT-5.pdfPSPC--UNIT-5.pdf
PSPC--UNIT-5.pdf
ArshiniGubbala3
 
btech-1picu-5pointerstructureunionandintrotofilehandling-150122010700-conver.ppt
btech-1picu-5pointerstructureunionandintrotofilehandling-150122010700-conver.pptbtech-1picu-5pointerstructureunionandintrotofilehandling-150122010700-conver.ppt
btech-1picu-5pointerstructureunionandintrotofilehandling-150122010700-conver.ppt
chintuyadav19
 
Pointers in C
Pointers in CPointers in C
Pointers in C
Monishkanungo
 
Pointers in C
Pointers in CPointers in C
Pointers in C
Vijayananda Ratnam Ch
 
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
 
PPS-POINTERS.pptx
PPS-POINTERS.pptxPPS-POINTERS.pptx
PPS-POINTERS.pptx
sajinis3
 
pointers.pptx
pointers.pptxpointers.pptx
pointers.pptx
s170883BesiVyshnavi
 
Pointers and single &multi dimentionalarrays.pptx
Pointers and single &multi dimentionalarrays.pptxPointers and single &multi dimentionalarrays.pptx
Pointers and single &multi dimentionalarrays.pptx
Ramakrishna Reddy Bijjam
 
Pointers
PointersPointers
Pointers
Lp Singh
 
ch08.ppt
ch08.pptch08.ppt
ch08.ppt
NewsMogul
 
Pointers-Computer programming
Pointers-Computer programmingPointers-Computer programming
Pointers-Computer programming
nmahi96
 
COM1407: Working with Pointers
COM1407: Working with PointersCOM1407: Working with Pointers
COM1407: Working with Pointers
Hemantha Kulathilake
 
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
 
Lecture 18 - Pointers
Lecture 18 - PointersLecture 18 - Pointers
Lecture 18 - Pointers
Md. Imran Hossain Showrov
 
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
 

Similar to C Pointers (20)

pointers.pptx
pointers.pptxpointers.pptx
pointers.pptx
 
PSPC--UNIT-5.pdf
PSPC--UNIT-5.pdfPSPC--UNIT-5.pdf
PSPC--UNIT-5.pdf
 
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
Pointers in CPointers in C
Pointers in C
 
Pointers in C
Pointers in CPointers in C
Pointers in C
 
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
 
PPS-POINTERS.pptx
PPS-POINTERS.pptxPPS-POINTERS.pptx
PPS-POINTERS.pptx
 
pointers.pptx
pointers.pptxpointers.pptx
pointers.pptx
 
Pointer
PointerPointer
Pointer
 
Pointers and single &multi dimentionalarrays.pptx
Pointers and single &multi dimentionalarrays.pptxPointers and single &multi dimentionalarrays.pptx
Pointers and single &multi dimentionalarrays.pptx
 
Pointers
PointersPointers
Pointers
 
ch08.ppt
ch08.pptch08.ppt
ch08.ppt
 
Pointers-Computer programming
Pointers-Computer programmingPointers-Computer programming
Pointers-Computer programming
 
COM1407: Working with Pointers
COM1407: Working with PointersCOM1407: Working with Pointers
COM1407: Working with Pointers
 
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
 
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
 
Advanced pointers
Advanced pointersAdvanced pointers
Advanced pointers
 
Lecture 18 - Pointers
Lecture 18 - PointersLecture 18 - Pointers
Lecture 18 - Pointers
 
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
 

Recently uploaded

Epistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI supportEpistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI support
Alan Dix
 
UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4
DianaGray10
 
Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...
Product School
 
FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdfFIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance
 
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdfSmart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
91mobiles
 
DevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA ConnectDevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA Connect
Kari Kakkonen
 
"Impact of front-end architecture on development cost", Viktor Turskyi
"Impact of front-end architecture on development cost", Viktor Turskyi"Impact of front-end architecture on development cost", Viktor Turskyi
"Impact of front-end architecture on development cost", Viktor Turskyi
Fwdays
 
How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...
Product School
 
Neuro-symbolic is not enough, we need neuro-*semantic*
Neuro-symbolic is not enough, we need neuro-*semantic*Neuro-symbolic is not enough, we need neuro-*semantic*
Neuro-symbolic is not enough, we need neuro-*semantic*
Frank van Harmelen
 
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered QualitySoftware Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Inflectra
 
Assuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyesAssuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyes
ThousandEyes
 
IOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptx
IOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptxIOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptx
IOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptx
Abida Shariff
 
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
BookNet Canada
 
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdfFIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance
 
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
Product School
 
Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........
Alison B. Lowndes
 
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
Product School
 
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
Product School
 
Search and Society: Reimagining Information Access for Radical Futures
Search and Society: Reimagining Information Access for Radical FuturesSearch and Society: Reimagining Information Access for Radical Futures
Search and Society: Reimagining Information Access for Radical Futures
Bhaskar Mitra
 
Key Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdfKey Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdf
Cheryl Hung
 

Recently uploaded (20)

Epistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI supportEpistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI support
 
UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4
 
Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...
 
FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdfFIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdf
 
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdfSmart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
 
DevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA ConnectDevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA Connect
 
"Impact of front-end architecture on development cost", Viktor Turskyi
"Impact of front-end architecture on development cost", Viktor Turskyi"Impact of front-end architecture on development cost", Viktor Turskyi
"Impact of front-end architecture on development cost", Viktor Turskyi
 
How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...
 
Neuro-symbolic is not enough, we need neuro-*semantic*
Neuro-symbolic is not enough, we need neuro-*semantic*Neuro-symbolic is not enough, we need neuro-*semantic*
Neuro-symbolic is not enough, we need neuro-*semantic*
 
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered QualitySoftware Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
 
Assuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyesAssuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyes
 
IOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptx
IOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptxIOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptx
IOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptx
 
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
 
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdfFIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
 
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
 
Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........
 
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
 
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
 
Search and Society: Reimagining Information Access for Radical Futures
Search and Society: Reimagining Information Access for Radical FuturesSearch and Society: Reimagining Information Access for Radical Futures
Search and Society: Reimagining Information Access for Radical Futures
 
Key Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdfKey Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdf
 

C Pointers

  • 1. Pointers in C Omar Mukhtar
  • 2. Outline  Review of concepts in previous lectures  Introduction to pointers  Pointers as function arguments  Pointers and arrays  Pointer arithmetic  Pointer-to-pointer
  • 3. Review and Background  Basic data types − Place-holders for numeric data  Integer numbers (int, short, long)  Real numbers (float, double)  Characters / symbols codes (char)  Arrays − A contiguous list of a particular data type  Functions − Give “name” to a particular piece of code − Modularization & reuse of code
  • 4. Pointers  The most useful and tricky concept in C language − Other high level languages abstract-out this concept  The most powerful construct too − Makes C very fast − Direct interaction with hardware − Solves very complicated programming problems
  • 5. What are pointers?  Just another kind of “placeholder” to hold “address” of memory location − Address is also a number − Itself resides on some memory location Memory Address Value 0x8004 ... 0x8008 variable A 129 0x800C ... 0x8010 0x8008 address of A 0x8014 ...
  • 6. What are pointers?  Declare variables a, b − int a, b;  Declare a pointer − int* pa;  Set value of a − a = 10;  Point pa to address of a − pa = &a;  Set value of a using pa − *pa = 12; pa = &b;
  • 7. Pointer Operators  “address-of” operator: & − Gets address of a variable  De-referencing operator: * − Accesses the memory location this pointer holds address of
  • 8. Pointers and Functions  A function can be passed arguments using basic data types − int prod(int a, int b) { return a*b; }  How to return multiple values from function? − void prod_and_sum(int a, int b, int*p, int* s) { *p = a*b; *s = a+b; }
  • 9. In & Out Arguments of Function  A function may like to pass values and get the result in the same variables. e.g. a Swap function.  void swap(int* a, int* b) { int c; c = *b; *b = *a; *a = c; }  int a = 5; b = 6;  swap(&a, &b);  // a hold 6 and b hold 5 now.
  • 10. Pointers and Arrays  Since arrays are a contiguous set of variables in memory, we can access them with pointers  int arr[5];  int *p = &arr[0];  *(p+0) = 1; // arr[0]  *(p+1) = 2; // arr[1]  *(p+2) = 4; // arr[2]  *(p+3) = 8; // arr[3]  ...
  • 11. Pointer Arithmetic  Arithmetic operators work as usual on ordinary data types. − int a = 1; a++; // a == 2  It gets a bit complicated when arithmetic operators are used on pointers  int* p = 0x8004; p++;  What does p hold now? 0x8005???  Compiler knows that p is a pointer to integer type data, so an increment to it should point to next integer in memory. Hence 0x8008.
  • 12. Pointer Arithmetic  So an arithmetic operator increases or decreases its contents by the size of data type it points to  int* pi = 0x8004; double* pd = 0x9004; char* pc = 0xa004;  pi++; // pi == 0x8008  pd++; // pd == 0x900c  pc++; // pc == 0xa005  Only '+' and '-' operator are allowed. '*' and '/' are meaningless.
  • 13. Pointer-to-Pointer  Pointer variable is just a place-holder of an address value, and itself is a variable. − Hence a pointer can hold address of other pointer variable. In that case it is called a “double pointer”.  int*p; int **pp; pp = &p;  e.g a function may like to return a pointer value  void pp_example(int** p) { *p = 0x8004; }  int *p; pp_example(&p);
  • 14. Pointer Pitfalls  Since pointer holds address of memory location, it must never be used without proper initialization.  An uninitialized pointer may hold address of some memory location that is protected by Operating System. In such case, de- referencing a pointer may crash the program.  An initialized pointer does not know the memory location, it is pointing to is, holds a valid value or some garbage.  A pointer cannot track boundaries of an array.