SlideShare uma empresa Scribd logo
1 de 29
Programming in C
Objectives


                In this session, you will learn to:
                   Declare and manipulate pointers
                   Use pointers to manipulate character arrays




     Ver. 1.0                                                    Slide 1 of 29
Programming in C
Declaring and Manipulating Pointers


                Every stored data item occupies one or more contiguous
                memory cells.
                Every cell in the memory has a unique address.
                Any reference to a variable, declared in memory, accesses
                the variable through the address of memory location.
                Pointers are variables, which contain the addresses of other
                variables (of any data type) in memory.




     Ver. 1.0                                                        Slide 2 of 29
Programming in C
Declaring Pointers


                A pointer variable must be declared before use in a
                program.
                A pointer variable is declared preceded by an asterisk.
                The declaration:
                 int *ptr; /* ptr is pointing to an int */
                 Indicates that ptr is a pointer to an integer variable.
                An uninitialized pointer may potentially point to any area of
                the memory and can cause a program to crash.
                A pointer can be initialized as follows:
                 ptr= &x;
                 In the preceding initialization, the pointer ptr is pointing to x.




     Ver. 1.0                                                                  Slide 3 of 29
Programming in C
Practice: 4.1


                1. In the following declaration:
                   float *ptr_to_float;
                   The pointer variable ptr_to_float is pointing to a
                   variable of type ____________.
                2. Is the following declaration valid?
                   *ptr_to_something;
                3. State whether True or False:
                   An integer is declared In the following declaration:
                   int *ptr_to_int;
                4. Is the following declaration valid?
                   int some_int, *ptr_to_int;




     Ver. 1.0                                                             Slide 4 of 29
Programming in C
Practice: 4.1 (Contd.)


                Solution:
                 1. float
                 2. No. When a pointer variable is being declared, the type of
                    variable to which it is pointing to (int, float, or char)
                    should also be indicated.
                 3. False. A pointer to an integer is being declared and not an
                    integer.
                 4. Yes. It is okay to club declaration of a certain type along with
                    pointers to the same type.




     Ver. 1.0                                                                Slide 5 of 29
Programming in C
Manipulating Pointers


                Pointers can be manipulated like variables.
                The unary operator * gives value of the variable a pointer is
                pointing to.
                The unary operator * is also termed as the indirection
                operator.
                The indirection operator can be used only on pointers.




     Ver. 1.0                                                         Slide 6 of 29
Programming in C
Practice: 4.2


                1. The symbol _________ is used to obtain the address of a
                   variable while the symbol__________ is used to obtain the
                   value of the variable to which a pointer is pointing to.
                2. With the following declarations:
                   int x, y, *ptr;
                   Which of the following are meaningful assignments?
                   a.   x = y;
                   b.   y=*ptr;
                   c.   x = ptr;
                   d.   x = &.ptr;
                   e.   ptr = &x;
                   f.   x = &y;




     Ver. 1.0                                                         Slide 7 of 29
Programming in C
Practice: 4.2 (Contd.)


                3. Consider the following sequence of statements and
                   complete the partially-filled table:
                  int x, y, *ptrl, *ptr2;
                  x = 65;
                  y = 89;
                  ptr1 = &x; /*ptrl points to x */
                  ptr2 = &y/;       /* ptr2 points to y */
                  x = *ptr1; /* statement A*)
                  ptr1 = ptr2:      /* statement B */
                  x = *ptr1; /* statement C*/
                  After statement   &x    x   &y    y    ptr1           ptr2
                      A             1006     1018
                      B
                      C

     Ver. 1.0                                                          Slide 8 of 29
Programming in C
Practice: 4.2 (Contd.)


                4. What is the output of the following sequence of statements:
                    int x, y, temp,*ptrl, *ptr2;       /* declare */
                    x = 23;
                    y = 37;
                    ptrl = &x;       /* ptrl points to x */
                    ptr2 = &y;       /* ptr2 points to y */
                    temp = *ptrl;
                    *ptr1 = *ptr2;
                    *ptr2 = temp;
                    printf(“x is %d while y is %d”, x, y);




     Ver. 1.0                                                          Slide 9 of 29
Programming in C
Practice: 4.2 (Contd.)


                Solution:




                            Microsoft Office
                        Word 97 - 2003 Document




     Ver. 1.0                                     Slide 10 of 29
Programming in C
Pointer Arithmetic


                Pointer Arithmetic:
                   Arithmetic operations can be performed on pointers.
                   Therefore, it is essential to declare a pointer as pointing to a
                   certain datatype so that when the pointer is incremented or
                   decremented, it moves by the appropriate number of bytes.
                   Consider the following statement:
                   ptr++;
                   It does not necessarily mean that ptr now points to the next
                   memory location. The memory location it will point to will
                   depend upon the datatype to which the pointer points.
                 – May be initialized when declared if done outside main().
                 – Consider the following example:
                     #include <stdio.h>
                     char movie[]= “Jurassic Park”;
                     main() {
                     char *ptr;
     Ver. 1.0                                                               Slide 11 of 29
Programming in C
Pointer Arithmetic (Contd.)


                Consider the following example:
                 #include <stdio.h>
                 char movie[]= “Jurassic Park”;
                 main() {
                 char *ptr;
                 ptr=movie;
                 printf(“%s”, movie); /* output: Jurassic Park */
                 printf(“%s”,ptr); /* output: Jurassic Park */
                 ptr++;
                 printf(“%s”,movie); /* output: Jurassic Park */
                 printf(“%s",prr); /* output: urassic Park */
                 ptr++;
                 printf(“%s”,movie); /* output; Jurassic Park */
                 printf(“%s”,ptr); /* output: rassic Park */
                 /* Note that the incrementing of the pointer ptr
                 does not in any way affect the pointer movie */
                 }



     Ver. 1.0                                               Slide 12 of 29
Programming in C
Practice: 4.3


                1. Consider the following code snippet:
                    #include <stdio.h>
                    int one_d[] = {l,2,3};
                    main(){
                    int *ptr;
                    ptr = one_d;
                    ptr +=3; /* statement A*/
                    printf(“%dn”, *ptr); /*statement B */
                    }
                    – After statement A is executed, the new address of ptr will be
                      ____ bytes more than the old address.
                    – State whether True or False:
                      The statement B will print 3.



     Ver. 1.0                                                              Slide 13 of 29
Programming in C
Practice: 4.3 (Contd.)


                Solution:
                 – 12 ( Size of integer = 4*3)
                 – False. Note that ptr is now pointing past the one-d array. So,
                   whatever is stored (junk or some value) at this address is
                   printed out. Again, note the dangers of arbitrary assignments
                   to pointer variables.




     Ver. 1.0                                                            Slide 14 of 29
Programming in C
Using Pointers to Manipulate Character Arrays


                Array name contains the address of the first element of the
                array.
                A pointer is a variable, which can store the address of another
                variable.
                It can be said that an array name is a pointer. Therefore, a
                pointer can be used to manipulate an array.




     Ver. 1.0                                                        Slide 15 of 29
Programming in C
One-Dimensional Arrays and Pointers


                One-Dimensional Arrays and Pointers:
                   Consider the following example:
                    #include <stdio.h>
                    char str[13]={“Jiggerypokry”};
                    char strl[]={ “Magic”};
                    main() {
                      char *ptr;
                      printf(“We are playing around with %s", str);
                    /* Output: We are playing around with Jiggerypokry*/
                    ptr=str ; /* ptr now points to whatever str is
                    pointing to */
                    printf(“We are playing around with %s" ,ptr);
                    /* Output: We are playing around with Jiggerypokry */
                    }




     Ver. 1.0                                                  Slide 16 of 29
Programming in C
One-Dimensional Arrays and Pointers (Contd.)


                In the preceding example the statement:
                ptr=str;
                Gives the impression that the two pointers are equal. However,
                there is a very subtle difference between str and ptr. str is a
                static pointer, which means that the address contained in str
                cannot be changed. While ptr is a dynamic pointer. The address
                in ptr can be changed.




     Ver. 1.0                                                       Slide 17 of 29
Programming in C
Practice: 4.4


                1. Given the declaration:
                     char some_string [10];
                     some_string points to _________.
                2. State whether True or False:
                   In the following declaration, the pointer err_msg contains a
                   valid address:
                     char *err_msg = “Some error message”;
                3. State whether True or False:
                   Consider the following declaration:
                     char *err_msg = “Some error message”;
                     It is more flexible than the following declaration:
                     char err_msg[19]=”Some error message”;



     Ver. 1.0                                                              Slide 18 of 29
Programming in C
Practice: 4.4 (Contd.)


                Solution:
                 1. some_string [0]
                 2. True
                 3. True. Note that one does not have to count the size of the
                    error message in the first declaration.




     Ver. 1.0                                                             Slide 19 of 29
Programming in C
Two-Dimensional Arrays and Pointers


                Two-dimensional arrays can be used to manipulate multiple
                strings at a time.
                String manipulation can also be done by using the array of
                pointers, as shown in the following example:
                   char *things[6]; /* declaring an array of 6
                   pointers to char */
                    things[0]=”Raindrops on roses”;
                    things[1]=”And Whiskers on kettles”;
                    things[2]=”Bright copper kettles”;
                    things[3]=”And warm woolen mittens”;
                    things[4]=”Brown paper packages tied up with
                    strings”;
                    things[5]=”These are a few of my favorite
                    things”;


     Ver. 1.0                                                      Slide 20 of 29
Programming in C
Two-Dimensional Arrays and Pointers (Contd.)


                The third line of the song can be printed by the following
                statement:
                 printf(“%s”, things[2]);
                 /*Output: Bright copper kettles */




     Ver. 1.0                                                           Slide 21 of 29
Programming in C
Practice: 4.5


                1. State whether True or False:
                   While declaring two-dimensional character arrays using
                   pointers, yon do not have to go through the tedium of
                   counting the number of characters in the longest string.
                2. Given the following error messages:
                       All's well
                       File not found
                       No read permission for file
                       Insufficient memory
                       No write permission for file
                   Write a program to print all the error messages on screen,
                   using pointers to array.



     Ver. 1.0                                                           Slide 22 of 29
Programming in C
Practice: 4.5 (Contd.)


                Solution:
                 1. True. New strings can be typed straight away within the {}. As
                    in:
                      char *err_msg_msg[]= {
                      “All's well”,
                      “File not found”,
                      “No read permission for file”,
                      “Insufficient memory”,
                      “No write permission for file”
                      };
                    The number of strings will define the size of the array.




     Ver. 1.0                                                             Slide 23 of 29
Programming in C
Practice: 4.5 (Contd.)


                2.   The program is:
                     # include<stdio.h>
                     # define ERRORS 5
                     char *err_msg[]= { /*Note the missing index*/
                     “All's well”,
                     “File not found”,
                     “No read permission for file”,
                     “Insufficient memory”,
                     “No write permission for file” };
                     main() {
                     int err_no;
                     for ( err_no = 0; err_no < ERRORS; err_no++ ) {
                     printf ( “nError message %d is : %sn”, err_no +
                         1, err_msg[err_no]); } }




     Ver. 1.0                                                   Slide 24 of 29
Programming in C
Two-Dimensional Arrays and Pointers (Contd.)


                Consider the following two-d array declaration:
                 int num[3][4]= {
                 {3, 6, 9, 12},
                 {15, 25, 30, 35},
                 {66, 77, 88, 99}
                 };
                 This statement actually declares an array of 3 pointers (constant)
                 num[0], num[l], and num[2] each containing the address of
                 the first element of three single-dimensional arrays.
                 The name of the array, num, contains the address of the first
                 element of the array of pointers (the address of num[0]).
                 Here,
                 *num is equal to num[0] because num[0] points to num[0][0].
                 *(*num) will give the value 3.
                 *num is equal to num[0].


     Ver. 1.0                                                             Slide 25 of 29
Programming in C
String-Handling Functions Using Pointers


                Pointers can be used to write string-handling functions.
                     Consider the following examples:
                     /* function to calculate length of a string*/
                     #include <stdio.h>
                     main() {
                     char *ptr, str[20];
                     int size=0;
                     printf(“nEnter string:”);
                     gets(str);
                     fflush(stdin);
                     for(ptr=str ; *ptr != '0'; ptr++) {
                     size++;
                     } printf(“String length is %d”, size);
                     }



     Ver. 1.0                                                        Slide 26 of 29
Programming in C
Using Pointers to Manipulate Character Arrays (Contd.)


                 /*function to check for a palindrome */
                 # include <stdio.h>
                 main() {
                 char str[50],*ptr,*lptr;
                 printf(“nEnter string :”);
                 gets(str); fflush(stdin);
                 for(lptr=str; *lptr !=’0'; lptr++);       /*reach
                 the string terminator */
                 lptr--; /*position on the last character */
                 for(ptr=str; ptr<=lptr; lptr--,ptr++) {
                 if(*ptr != *lptr)
                 break;}
                 if(ptr>lptr)
                 printf(“%s is a palindrome” );
                 else
                 printf(“%s is not a palindrome");
                 }
     Ver. 1.0                                                Slide 27 of 29
Programming in C
Summary


               In this session, you learned that:
                  A pointer is a variable, which contains the address of some
                  other variable in memory.
                  A pointer may point to a variable of any data type.
                  A pointer can point to any portion of the memory.
                  A pointer variable is declared as:
                    datatype *<pointer variable name>
                  A pointer variable is initialized as:
                    pointer variable name> = &<variable name to which
                    the pointer will point to>
                – The & returns the address of the variable.
                – The * before a pointer name gives the value of the variable to
                  which it is pointing.



    Ver. 1.0                                                             Slide 28 of 29
Programming in C
Summary (Contd.)


               Pointers can also be subjected to arithmetic.
               Incrementing a pointer by 1 makes it point to a memory
               location given by the formula:
                New address = Old address + Scaling factor
               One-dimensional character arrays can be declared by
               declaring a pointer and initializing it.
               The name of a character array is actually a pointer to the first
               element of the array.
               Two-dimensional character arrays can also be declared by
               using pointers.




    Ver. 1.0                                                            Slide 29 of 29

Mais conteúdo relacionado

Mais procurados

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 handlingRai University
 
Types of pointer in C
Types of pointer in CTypes of pointer in C
Types of pointer in Crgnikate
 
Tutorial on c language programming
Tutorial on c language programmingTutorial on c language programming
Tutorial on c language programmingSudheer Kiran
 
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 caoVietJackTeam
 
C programming & data structure [character strings & string functions]
C programming & data structure   [character strings & string functions]C programming & data structure   [character strings & string functions]
C programming & data structure [character strings & string functions]MomenMostafa
 
Dart function - Recursive functions
Dart function - Recursive functionsDart function - Recursive functions
Dart function - Recursive functionsKoAungThuOo1
 
C programming - Pointer and DMA
C programming - Pointer and DMAC programming - Pointer and DMA
C programming - Pointer and DMAAchyut Devkota
 
5. using variables, data, expressions and constants
5. using variables, data, expressions and constants5. using variables, data, expressions and constants
5. using variables, data, expressions and constantsCtOlaf
 

Mais procurados (20)

Commons Nabla
Commons NablaCommons Nabla
Commons Nabla
 
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
 
Void pointer in c
Void pointer in cVoid pointer in c
Void pointer in c
 
Types of pointer in C
Types of pointer in CTypes of pointer in C
Types of pointer in C
 
Tutorial on c language programming
Tutorial on c language programmingTutorial on c language programming
Tutorial on c language programming
 
Chtp414
Chtp414Chtp414
Chtp414
 
Lecture 17 - Strings
Lecture 17 - StringsLecture 17 - Strings
Lecture 17 - Strings
 
C pointers
C pointersC pointers
C pointers
 
oop Lecture 17
oop Lecture 17oop Lecture 17
oop Lecture 17
 
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
 
Lk module5 pointers
Lk module5 pointersLk module5 pointers
Lk module5 pointers
 
Pointer in C
Pointer in CPointer in C
Pointer in C
 
Dft2
Dft2Dft2
Dft2
 
C programming & data structure [character strings & string functions]
C programming & data structure   [character strings & string functions]C programming & data structure   [character strings & string functions]
C programming & data structure [character strings & string functions]
 
Lecture 18 - Pointers
Lecture 18 - PointersLecture 18 - Pointers
Lecture 18 - Pointers
 
Dart function - Recursive functions
Dart function - Recursive functionsDart function - Recursive functions
Dart function - Recursive functions
 
13 Jo P Jan 08
13 Jo P Jan 0813 Jo P Jan 08
13 Jo P Jan 08
 
C programming - Pointer and DMA
C programming - Pointer and DMAC programming - Pointer and DMA
C programming - Pointer and DMA
 
5. using variables, data, expressions and constants
5. using variables, data, expressions and constants5. using variables, data, expressions and constants
5. using variables, data, expressions and constants
 
C pointer
C pointerC pointer
C pointer
 

Destaque

C programming session 08
C programming session 08C programming session 08
C programming session 08AjayBahoriya
 
C programming session 16
C programming session 16C programming session 16
C programming session 16AjayBahoriya
 
Research and planning March
Research and planning  March Research and planning  March
Research and planning March hannahata2012
 
C programming session 11
C programming session 11C programming session 11
C programming session 11AjayBahoriya
 
C programming session 01
C programming session 01C programming session 01
C programming session 01AjayBahoriya
 
C programming session 02
C programming session 02C programming session 02
C programming session 02AjayBahoriya
 
C programming session 10
C programming session 10C programming session 10
C programming session 10AjayBahoriya
 
How does your media product represent particular social
How does your media product represent particular socialHow does your media product represent particular social
How does your media product represent particular socialhannahata2012
 
C programming session 04
C programming session 04C programming session 04
C programming session 04Dushmanta Nath
 
C programming session 05
C programming session 05C programming session 05
C programming session 05Dushmanta Nath
 

Destaque (10)

C programming session 08
C programming session 08C programming session 08
C programming session 08
 
C programming session 16
C programming session 16C programming session 16
C programming session 16
 
Research and planning March
Research and planning  March Research and planning  March
Research and planning March
 
C programming session 11
C programming session 11C programming session 11
C programming session 11
 
C programming session 01
C programming session 01C programming session 01
C programming session 01
 
C programming session 02
C programming session 02C programming session 02
C programming session 02
 
C programming session 10
C programming session 10C programming session 10
C programming session 10
 
How does your media product represent particular social
How does your media product represent particular socialHow does your media product represent particular social
How does your media product represent particular social
 
C programming session 04
C programming session 04C programming session 04
C programming session 04
 
C programming session 05
C programming session 05C programming session 05
C programming session 05
 

Semelhante a Learn pointers and manipulate character arrays in C

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 handlingRai 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 handlingRai University
 
Preprocessor directives
Preprocessor directivesPreprocessor directives
Preprocessor directivesVikash Dhal
 
Fortran introduction
Fortran introductionFortran introduction
Fortran introductionsanthosh833
 
Complicated declarations in c
Complicated declarations in cComplicated declarations in c
Complicated declarations in cRahul Budholiya
 
presentation_c_basics_1589366177_381682.pptx
presentation_c_basics_1589366177_381682.pptxpresentation_c_basics_1589366177_381682.pptx
presentation_c_basics_1589366177_381682.pptxKrishanPalSingh39
 
Pointers in c - Mohammad Salman
Pointers in c - Mohammad SalmanPointers in c - Mohammad Salman
Pointers in c - Mohammad SalmanMohammadSalman129
 
Object Oriented Technologies
Object Oriented TechnologiesObject Oriented Technologies
Object Oriented TechnologiesUmesh Nikam
 
btech-1picu-5pointerstructureunionandintrotofilehandling-150122010700-conver.ppt
btech-1picu-5pointerstructureunionandintrotofilehandling-150122010700-conver.pptbtech-1picu-5pointerstructureunionandintrotofilehandling-150122010700-conver.ppt
btech-1picu-5pointerstructureunionandintrotofilehandling-150122010700-conver.pptchintuyadav19
 

Semelhante a Learn pointers and manipulate character arrays in C (20)

C programming session8
C programming  session8C programming  session8
C programming session8
 
C programming session8
C programming  session8C programming  session8
C programming session8
 
Advanced pointers
Advanced pointersAdvanced pointers
Advanced pointers
 
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
 
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
 
Preprocessor directives
Preprocessor directivesPreprocessor directives
Preprocessor directives
 
Pointers
PointersPointers
Pointers
 
Pointers
PointersPointers
Pointers
 
Pointer.pptx
Pointer.pptxPointer.pptx
Pointer.pptx
 
Fortran introduction
Fortran introductionFortran introduction
Fortran introduction
 
Types of pointer
Types of pointerTypes of pointer
Types of pointer
 
POINTERS.pptx
POINTERS.pptxPOINTERS.pptx
POINTERS.pptx
 
Complicated declarations in c
Complicated declarations in cComplicated declarations in c
Complicated declarations in c
 
presentation_c_basics_1589366177_381682.pptx
presentation_c_basics_1589366177_381682.pptxpresentation_c_basics_1589366177_381682.pptx
presentation_c_basics_1589366177_381682.pptx
 
COM1407: Working with Pointers
COM1407: Working with PointersCOM1407: Working with Pointers
COM1407: Working with Pointers
 
Pointers in c - Mohammad Salman
Pointers in c - Mohammad SalmanPointers in c - Mohammad Salman
Pointers in c - Mohammad Salman
 
Object Oriented Technologies
Object Oriented TechnologiesObject Oriented Technologies
Object Oriented Technologies
 
Computer Programming- Lecture 7
Computer Programming- Lecture 7Computer Programming- Lecture 7
Computer Programming- Lecture 7
 
btech-1picu-5pointerstructureunionandintrotofilehandling-150122010700-conver.ppt
btech-1picu-5pointerstructureunionandintrotofilehandling-150122010700-conver.pptbtech-1picu-5pointerstructureunionandintrotofilehandling-150122010700-conver.ppt
btech-1picu-5pointerstructureunionandintrotofilehandling-150122010700-conver.ppt
 
C introduction by piyushkumar
C introduction by piyushkumarC introduction by piyushkumar
C introduction by piyushkumar
 

Último

Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxLoriGlavin3
 
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24Mark Goldstein
 
QCon London: Mastering long-running processes in modern architectures
QCon London: Mastering long-running processes in modern architecturesQCon London: Mastering long-running processes in modern architectures
QCon London: Mastering long-running processes in modern architecturesBernd Ruecker
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024Lonnie McRorey
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxLoriGlavin3
 
MuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotes
MuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotesMuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotes
MuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotesManik S Magar
 
Varsha Sewlal- Cyber Attacks on Critical Critical Infrastructure
Varsha Sewlal- Cyber Attacks on Critical Critical InfrastructureVarsha Sewlal- Cyber Attacks on Critical Critical Infrastructure
Varsha Sewlal- Cyber Attacks on Critical Critical Infrastructureitnewsafrica
 
Bridging Between CAD & GIS: 6 Ways to Automate Your Data Integration
Bridging Between CAD & GIS:  6 Ways to Automate Your Data IntegrationBridging Between CAD & GIS:  6 Ways to Automate Your Data Integration
Bridging Between CAD & GIS: 6 Ways to Automate Your Data Integrationmarketing932765
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxLoriGlavin3
 
Microsoft 365 Copilot: How to boost your productivity with AI – Part one: Ado...
Microsoft 365 Copilot: How to boost your productivity with AI – Part one: Ado...Microsoft 365 Copilot: How to boost your productivity with AI – Part one: Ado...
Microsoft 365 Copilot: How to boost your productivity with AI – Part one: Ado...Nikki Chapple
 
Top 10 Hubspot Development Companies in 2024
Top 10 Hubspot Development Companies in 2024Top 10 Hubspot Development Companies in 2024
Top 10 Hubspot Development Companies in 2024TopCSSGallery
 
Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...Farhan Tariq
 
Connecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdfConnecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdfNeo4j
 
2024 April Patch Tuesday
2024 April Patch Tuesday2024 April Patch Tuesday
2024 April Patch TuesdayIvanti
 
Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024Hiroshi SHIBATA
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxLoriGlavin3
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxLoriGlavin3
 
So einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdfSo einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdfpanagenda
 
Modern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better StrongerModern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better Strongerpanagenda
 

Último (20)

Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
 
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
 
QCon London: Mastering long-running processes in modern architectures
QCon London: Mastering long-running processes in modern architecturesQCon London: Mastering long-running processes in modern architectures
QCon London: Mastering long-running processes in modern architectures
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
 
MuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotes
MuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotesMuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotes
MuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotes
 
Varsha Sewlal- Cyber Attacks on Critical Critical Infrastructure
Varsha Sewlal- Cyber Attacks on Critical Critical InfrastructureVarsha Sewlal- Cyber Attacks on Critical Critical Infrastructure
Varsha Sewlal- Cyber Attacks on Critical Critical Infrastructure
 
Bridging Between CAD & GIS: 6 Ways to Automate Your Data Integration
Bridging Between CAD & GIS:  6 Ways to Automate Your Data IntegrationBridging Between CAD & GIS:  6 Ways to Automate Your Data Integration
Bridging Between CAD & GIS: 6 Ways to Automate Your Data Integration
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
 
Microsoft 365 Copilot: How to boost your productivity with AI – Part one: Ado...
Microsoft 365 Copilot: How to boost your productivity with AI – Part one: Ado...Microsoft 365 Copilot: How to boost your productivity with AI – Part one: Ado...
Microsoft 365 Copilot: How to boost your productivity with AI – Part one: Ado...
 
Top 10 Hubspot Development Companies in 2024
Top 10 Hubspot Development Companies in 2024Top 10 Hubspot Development Companies in 2024
Top 10 Hubspot Development Companies in 2024
 
Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...
 
Connecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdfConnecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdf
 
2024 April Patch Tuesday
2024 April Patch Tuesday2024 April Patch Tuesday
2024 April Patch Tuesday
 
Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptx
 
So einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdfSo einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdf
 
Modern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better StrongerModern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
 

Learn pointers and manipulate character arrays in C

  • 1. Programming in C Objectives In this session, you will learn to: Declare and manipulate pointers Use pointers to manipulate character arrays Ver. 1.0 Slide 1 of 29
  • 2. Programming in C Declaring and Manipulating Pointers Every stored data item occupies one or more contiguous memory cells. Every cell in the memory has a unique address. Any reference to a variable, declared in memory, accesses the variable through the address of memory location. Pointers are variables, which contain the addresses of other variables (of any data type) in memory. Ver. 1.0 Slide 2 of 29
  • 3. Programming in C Declaring Pointers A pointer variable must be declared before use in a program. A pointer variable is declared preceded by an asterisk. The declaration: int *ptr; /* ptr is pointing to an int */ Indicates that ptr is a pointer to an integer variable. An uninitialized pointer may potentially point to any area of the memory and can cause a program to crash. A pointer can be initialized as follows: ptr= &x; In the preceding initialization, the pointer ptr is pointing to x. Ver. 1.0 Slide 3 of 29
  • 4. Programming in C Practice: 4.1 1. In the following declaration: float *ptr_to_float; The pointer variable ptr_to_float is pointing to a variable of type ____________. 2. Is the following declaration valid? *ptr_to_something; 3. State whether True or False: An integer is declared In the following declaration: int *ptr_to_int; 4. Is the following declaration valid? int some_int, *ptr_to_int; Ver. 1.0 Slide 4 of 29
  • 5. Programming in C Practice: 4.1 (Contd.) Solution: 1. float 2. No. When a pointer variable is being declared, the type of variable to which it is pointing to (int, float, or char) should also be indicated. 3. False. A pointer to an integer is being declared and not an integer. 4. Yes. It is okay to club declaration of a certain type along with pointers to the same type. Ver. 1.0 Slide 5 of 29
  • 6. Programming in C Manipulating Pointers Pointers can be manipulated like variables. The unary operator * gives value of the variable a pointer is pointing to. The unary operator * is also termed as the indirection operator. The indirection operator can be used only on pointers. Ver. 1.0 Slide 6 of 29
  • 7. Programming in C Practice: 4.2 1. The symbol _________ is used to obtain the address of a variable while the symbol__________ is used to obtain the value of the variable to which a pointer is pointing to. 2. With the following declarations: int x, y, *ptr; Which of the following are meaningful assignments? a. x = y; b. y=*ptr; c. x = ptr; d. x = &.ptr; e. ptr = &x; f. x = &y; Ver. 1.0 Slide 7 of 29
  • 8. Programming in C Practice: 4.2 (Contd.) 3. Consider the following sequence of statements and complete the partially-filled table: int x, y, *ptrl, *ptr2; x = 65; y = 89; ptr1 = &x; /*ptrl points to x */ ptr2 = &y/; /* ptr2 points to y */ x = *ptr1; /* statement A*) ptr1 = ptr2: /* statement B */ x = *ptr1; /* statement C*/ After statement &x x &y y ptr1 ptr2 A 1006 1018 B C Ver. 1.0 Slide 8 of 29
  • 9. Programming in C Practice: 4.2 (Contd.) 4. What is the output of the following sequence of statements: int x, y, temp,*ptrl, *ptr2; /* declare */ x = 23; y = 37; ptrl = &x; /* ptrl points to x */ ptr2 = &y; /* ptr2 points to y */ temp = *ptrl; *ptr1 = *ptr2; *ptr2 = temp; printf(“x is %d while y is %d”, x, y); Ver. 1.0 Slide 9 of 29
  • 10. Programming in C Practice: 4.2 (Contd.) Solution: Microsoft Office Word 97 - 2003 Document Ver. 1.0 Slide 10 of 29
  • 11. Programming in C Pointer Arithmetic Pointer Arithmetic: Arithmetic operations can be performed on pointers. Therefore, it is essential to declare a pointer as pointing to a certain datatype so that when the pointer is incremented or decremented, it moves by the appropriate number of bytes. Consider the following statement: ptr++; It does not necessarily mean that ptr now points to the next memory location. The memory location it will point to will depend upon the datatype to which the pointer points. – May be initialized when declared if done outside main(). – Consider the following example: #include <stdio.h> char movie[]= “Jurassic Park”; main() { char *ptr; Ver. 1.0 Slide 11 of 29
  • 12. Programming in C Pointer Arithmetic (Contd.) Consider the following example: #include <stdio.h> char movie[]= “Jurassic Park”; main() { char *ptr; ptr=movie; printf(“%s”, movie); /* output: Jurassic Park */ printf(“%s”,ptr); /* output: Jurassic Park */ ptr++; printf(“%s”,movie); /* output: Jurassic Park */ printf(“%s",prr); /* output: urassic Park */ ptr++; printf(“%s”,movie); /* output; Jurassic Park */ printf(“%s”,ptr); /* output: rassic Park */ /* Note that the incrementing of the pointer ptr does not in any way affect the pointer movie */ } Ver. 1.0 Slide 12 of 29
  • 13. Programming in C Practice: 4.3 1. Consider the following code snippet: #include <stdio.h> int one_d[] = {l,2,3}; main(){ int *ptr; ptr = one_d; ptr +=3; /* statement A*/ printf(“%dn”, *ptr); /*statement B */ } – After statement A is executed, the new address of ptr will be ____ bytes more than the old address. – State whether True or False: The statement B will print 3. Ver. 1.0 Slide 13 of 29
  • 14. Programming in C Practice: 4.3 (Contd.) Solution: – 12 ( Size of integer = 4*3) – False. Note that ptr is now pointing past the one-d array. So, whatever is stored (junk or some value) at this address is printed out. Again, note the dangers of arbitrary assignments to pointer variables. Ver. 1.0 Slide 14 of 29
  • 15. Programming in C Using Pointers to Manipulate Character Arrays Array name contains the address of the first element of the array. A pointer is a variable, which can store the address of another variable. It can be said that an array name is a pointer. Therefore, a pointer can be used to manipulate an array. Ver. 1.0 Slide 15 of 29
  • 16. Programming in C One-Dimensional Arrays and Pointers One-Dimensional Arrays and Pointers: Consider the following example: #include <stdio.h> char str[13]={“Jiggerypokry”}; char strl[]={ “Magic”}; main() { char *ptr; printf(“We are playing around with %s", str); /* Output: We are playing around with Jiggerypokry*/ ptr=str ; /* ptr now points to whatever str is pointing to */ printf(“We are playing around with %s" ,ptr); /* Output: We are playing around with Jiggerypokry */ } Ver. 1.0 Slide 16 of 29
  • 17. Programming in C One-Dimensional Arrays and Pointers (Contd.) In the preceding example the statement: ptr=str; Gives the impression that the two pointers are equal. However, there is a very subtle difference between str and ptr. str is a static pointer, which means that the address contained in str cannot be changed. While ptr is a dynamic pointer. The address in ptr can be changed. Ver. 1.0 Slide 17 of 29
  • 18. Programming in C Practice: 4.4 1. Given the declaration: char some_string [10]; some_string points to _________. 2. State whether True or False: In the following declaration, the pointer err_msg contains a valid address: char *err_msg = “Some error message”; 3. State whether True or False: Consider the following declaration: char *err_msg = “Some error message”; It is more flexible than the following declaration: char err_msg[19]=”Some error message”; Ver. 1.0 Slide 18 of 29
  • 19. Programming in C Practice: 4.4 (Contd.) Solution: 1. some_string [0] 2. True 3. True. Note that one does not have to count the size of the error message in the first declaration. Ver. 1.0 Slide 19 of 29
  • 20. Programming in C Two-Dimensional Arrays and Pointers Two-dimensional arrays can be used to manipulate multiple strings at a time. String manipulation can also be done by using the array of pointers, as shown in the following example: char *things[6]; /* declaring an array of 6 pointers to char */ things[0]=”Raindrops on roses”; things[1]=”And Whiskers on kettles”; things[2]=”Bright copper kettles”; things[3]=”And warm woolen mittens”; things[4]=”Brown paper packages tied up with strings”; things[5]=”These are a few of my favorite things”; Ver. 1.0 Slide 20 of 29
  • 21. Programming in C Two-Dimensional Arrays and Pointers (Contd.) The third line of the song can be printed by the following statement: printf(“%s”, things[2]); /*Output: Bright copper kettles */ Ver. 1.0 Slide 21 of 29
  • 22. Programming in C Practice: 4.5 1. State whether True or False: While declaring two-dimensional character arrays using pointers, yon do not have to go through the tedium of counting the number of characters in the longest string. 2. Given the following error messages: All's well File not found No read permission for file Insufficient memory No write permission for file Write a program to print all the error messages on screen, using pointers to array. Ver. 1.0 Slide 22 of 29
  • 23. Programming in C Practice: 4.5 (Contd.) Solution: 1. True. New strings can be typed straight away within the {}. As in: char *err_msg_msg[]= { “All's well”, “File not found”, “No read permission for file”, “Insufficient memory”, “No write permission for file” }; The number of strings will define the size of the array. Ver. 1.0 Slide 23 of 29
  • 24. Programming in C Practice: 4.5 (Contd.) 2. The program is: # include<stdio.h> # define ERRORS 5 char *err_msg[]= { /*Note the missing index*/ “All's well”, “File not found”, “No read permission for file”, “Insufficient memory”, “No write permission for file” }; main() { int err_no; for ( err_no = 0; err_no < ERRORS; err_no++ ) { printf ( “nError message %d is : %sn”, err_no + 1, err_msg[err_no]); } } Ver. 1.0 Slide 24 of 29
  • 25. Programming in C Two-Dimensional Arrays and Pointers (Contd.) Consider the following two-d array declaration: int num[3][4]= { {3, 6, 9, 12}, {15, 25, 30, 35}, {66, 77, 88, 99} }; This statement actually declares an array of 3 pointers (constant) num[0], num[l], and num[2] each containing the address of the first element of three single-dimensional arrays. The name of the array, num, contains the address of the first element of the array of pointers (the address of num[0]). Here, *num is equal to num[0] because num[0] points to num[0][0]. *(*num) will give the value 3. *num is equal to num[0]. Ver. 1.0 Slide 25 of 29
  • 26. Programming in C String-Handling Functions Using Pointers Pointers can be used to write string-handling functions. Consider the following examples: /* function to calculate length of a string*/ #include <stdio.h> main() { char *ptr, str[20]; int size=0; printf(“nEnter string:”); gets(str); fflush(stdin); for(ptr=str ; *ptr != '0'; ptr++) { size++; } printf(“String length is %d”, size); } Ver. 1.0 Slide 26 of 29
  • 27. Programming in C Using Pointers to Manipulate Character Arrays (Contd.) /*function to check for a palindrome */ # include <stdio.h> main() { char str[50],*ptr,*lptr; printf(“nEnter string :”); gets(str); fflush(stdin); for(lptr=str; *lptr !=’0'; lptr++); /*reach the string terminator */ lptr--; /*position on the last character */ for(ptr=str; ptr<=lptr; lptr--,ptr++) { if(*ptr != *lptr) break;} if(ptr>lptr) printf(“%s is a palindrome” ); else printf(“%s is not a palindrome"); } Ver. 1.0 Slide 27 of 29
  • 28. Programming in C Summary In this session, you learned that: A pointer is a variable, which contains the address of some other variable in memory. A pointer may point to a variable of any data type. A pointer can point to any portion of the memory. A pointer variable is declared as: datatype *<pointer variable name> A pointer variable is initialized as: pointer variable name> = &<variable name to which the pointer will point to> – The & returns the address of the variable. – The * before a pointer name gives the value of the variable to which it is pointing. Ver. 1.0 Slide 28 of 29
  • 29. Programming in C Summary (Contd.) Pointers can also be subjected to arithmetic. Incrementing a pointer by 1 makes it point to a memory location given by the formula: New address = Old address + Scaling factor One-dimensional character arrays can be declared by declaring a pointer and initializing it. The name of a character array is actually a pointer to the first element of the array. Two-dimensional character arrays can also be declared by using pointers. Ver. 1.0 Slide 29 of 29

Notas do Editor

  1. Begin the session by explaining the objectives of the session.
  2. Pointers contain addresses of variables of a specific type. Hence, the pointer and the variable to which it is pointing should be of the same type. The number of bytes used by the pointer to hold an address does not depend on the type of the variable the variable it is pointing to. The number of bytes used by a pointer is generally 4 bytes, or 2 bytes in some implementations. Type casting may be used to initialize a pointer with the address of a variable of a different type. For example, the following code is valid : char *ptr ; int i = 4 ; ptr = (char *) (&amp;i) ; though this is seldom done. Pointers to type void can contain addresses of any data. It does not make sense to do any arithmetic with these pointers.
  3. Use this slide to test the student’s understanding on declaring pointers.
  4. Preceding a pointer with ampersand will yield the address of the pointer itself, and can be stored in a pointer to a pointer. Consider the following code: char *ptr, **pptr, chr; ptr = &amp;chr; /* address of a character */ pptr = &amp;ptr; /* address of a pointer */
  5. Use this slide to test the student’s understanding on declaring and initializing pointers.
  6. Generally, only the operators + and – are used with pointers. This results in the address in the pointer getting altered by a value equal to the size of the data type it is associated with. The following declaration is for a pointer to an array of 10 elements: char (*ptr) [10] ; /* note, it is not an array of pointers */ If the pointer ptr is initialized and contains the address 100 , ptr++ results in the address in ptr being scaled by 10. ptr will now contain 110.
  7. Use this slide to test the student’s understanding on pointers arithmetic.
  8. Use this slide to test the student’s understanding on one-dimensional arrays and pointers.
  9. Use this slide to test the student’s understanding on 2-D arrays and pointers.
  10. Use this and the next slide to summarize the session.