SlideShare uma empresa Scribd logo
1 de 14
Baixar para ler offline
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.

Mais conteúdo relacionado

Mais procurados

Pointers in c
Pointers in cPointers in c
Pointers in c
Mohd Arif
 
Data types in C language
Data types in C languageData types in C language
Data types in C language
kashyap399
 

Mais procurados (20)

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 in C
Pointers in CPointers in C
Pointers in C
 
Pointers C programming
Pointers  C programmingPointers  C programming
Pointers C programming
 
Presentation on pointer.
Presentation on pointer.Presentation on pointer.
Presentation on pointer.
 
Pointer in C
Pointer in CPointer in C
Pointer in C
 
Pointers in c++
Pointers in c++Pointers in c++
Pointers in c++
 
Programming in c Arrays
Programming in c ArraysProgramming in c Arrays
Programming in c Arrays
 
Pointers in C Language
Pointers in C LanguagePointers in C Language
Pointers in C Language
 
Function in C Programming
Function in C ProgrammingFunction in C Programming
Function in C Programming
 
String functions in C
String functions in CString functions in C
String functions in C
 
Pointer in c
Pointer in cPointer in c
Pointer in c
 
Pointer in C++
Pointer in C++Pointer in C++
Pointer in C++
 
Functions in c
Functions in cFunctions in c
Functions in c
 
Control statements in c
Control statements in cControl statements in c
Control statements in c
 
Pointers in c
Pointers in cPointers in c
Pointers in c
 
Pointers in C
Pointers in CPointers in C
Pointers in C
 
File handling in c
File handling in cFile handling in c
File handling in c
 
Enumerated data types in C
Enumerated data types in CEnumerated data types in C
Enumerated data types in C
 
Data types in C language
Data types in C languageData types in C language
Data types in C language
 
pointers
pointerspointers
pointers
 

Semelhante a C Pointers

btech-1picu-5pointerstructureunionandintrotofilehandling-150122010700-conver.ppt
btech-1picu-5pointerstructureunionandintrotofilehandling-150122010700-conver.pptbtech-1picu-5pointerstructureunionandintrotofilehandling-150122010700-conver.ppt
btech-1picu-5pointerstructureunionandintrotofilehandling-150122010700-conver.ppt
chintuyadav19
 

Semelhante a 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
 
Basics of pointer, pointer expressions, pointer to pointer and pointer in fun...
Basics of pointer, pointer expressions, pointer to pointer and pointer in fun...Basics of pointer, pointer expressions, pointer to pointer and pointer in fun...
Basics of pointer, pointer expressions, pointer to pointer and pointer in fun...
 
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
 
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
 
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
 

Último

Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
WSO2
 

Último (20)

Vector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxVector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptx
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with Milvus
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
Six Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal OntologySix Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal Ontology
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.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.