SlideShare a Scribd company logo
By- mynk


Happy to help…!    1
Review of arrays
 There are no array variables in C – only array
  names
   Each name refers to a constant pointer
   Space for array elements is allocated at declaration
    time
 Can’t change where the array name refers to…
   but you can change the array elements,
    via pointer arithmetic
                               ???     ???     ???         ???
              (int [])         (int)   (int)   (int)       (int)

                     m
int m[4];

                                                 Happy to help…!   2
Subscripts and pointer
  arithmetic
 array[subscript]   equivalent to *(array   +
  (subscript))



 Strange but true: Given earlier declaration of m,
  the expression 2[m] is legal!
   Not only that: it’s equivalent to        *(2+m)
                                        *(m+2)
                                        m[2]



                                                 Happy to help…! 3
Array names and pointer
   variables,       ??? ???                                  ???
   playing together
    int m[3];
   subscript OK         (int [])
                                          (int)    (int)     (int)

with pointer variable     m


                                                  (int [])


    int *mid = m + 1;                                 mid
                                                                 (int [])

                                                                     right
    int *right = mid[1];
                                   (int [])

                                     left
    int *left = mid[-1];                                             (int [])


                       compiler may not catch this –                 beyond
    int *beyond = mid[2]; environment certainly won’t
                    runtime

                                                                Happy to help…!   4
Array names as function
arguments
 In C, arguments are passed “by value”
   A temporary copy of each argument is created, solely for use within
    the function call
void f(int x, int *y) { … }

void g(…) {                     17          42              17
  int a = 17, b = 42;           (int)       (int)          (int)        (int [])

  f(a, &b);                             a           b              x           y
  …
}                                                   g                              f
 Pass-by-value is “safe” in that the function plays only in its
  “sandbox” of temporary variables –
   can’t alter the values of variables in the callee (except via the return
    value)


                                                           Happy to help…!         5
Array names as function
    arguments
     But, functions that take arrays as arguments can
      exhibit what looks like “pass-by-reference”
      behavior, where the array passed in by the callee
      does get changed
       Remember the special status of arrays in C –
        They are basically just pointers.
       So arrays are indeed passed by value –
        but only the pointer is copied, not the array elements!
         Note the advantage in efficiency (avoids a lot of copying)
         But – the pointer copy points to the same elements as
          the callee’s array
         These elements can easily be modified via pointer
          manipulation
                                                            Happy to help…!
6
Array names as function
arguments
 The strcpy “string copy” function puts this
  “pseudo” call-by-reference behavior to good
  use
void strcpy(char *buffer, char const *string);
void f(…) {
  char original[4] = ″dog″; g
                  d      o                   NUL                (char [])
   (char [])
  char copy[4]; (char) (char) (char)         (char)

 origin                                                           string
  strcpy(copy, original);
 al
} (char [])       d
                 ???     o
                        ???     g
                               ???           NUL
                                             ???                (char [])
                  (char)   (char)   (char)   (char)

     copy                                                         buffer
            f                                                       strcpy
                                                      Happy to help…!       7
When can array size be
omitted?
 There are a couple of contexts in which an array
  declaration need not have a size specified:
   Parameter declaration:
    int strlen(char string[]);
     As we’ve seen, the elements of the array argument are
      not copied, so the function doesn’t need to know how
      many elements there are.
   Array initialization:
    int vector[] = {1, 2, 3, 4, 5};
     In this case, just enough space is allocated to fit all (five)
      elements of the initializer list

                                                       Happy to help…!   8
Multidimensional arrays

      How to interpret a declaration like:
          int d[2][4];
      This is an array with two elements:
           Each element is an array of four int values
      The elements are laid out sequentially in
          memory, just like a one-dimensional array
             Row-major order: the(int)
                                  elements of the rightmost
                                               (int)
 (int)     (int) (int)  (int)         (int)            (int)


            subscript are stored contiguously
          d[0][1]                                            d[1][2]    d[1][3]
d[0][0]             d[0][2]   d[0][3]    d[1][0]   d[1][1]
                                  d[0]                                      d[1]



                                                                   Happy to help…!   9
Subscripting in a
    multidimensional array
     int   d[2][4];

                *(d+1) [1]
              *(*(d+1)+2) [2]
                    d                                Then increment by the
                                                        size of 2 ints


                               Increment by the size of
                                  1 array of 4 ints



 (int)      (int)     (int)       (int)      (int)        (int)    (int)           (int)

d[0][0]    d[0][1]   d[0][2]     d[0][3]    d[1][0]    d[1][1]    d[1][2]        d[1][3]

                                     d[0]                                            d[1]


                                                                             Happy to help…!   10
Why do we care about
storage order?
 If you keep within the “paradigm” of the
  multidimensional array, the order doesn’t
  matter…
 But if you use tricks with pointer arithmetic,
  it matters a lot                    0    1    2           3

 It also matters for initialization 4     5    6           7

   To initialize d like this:
     use this:
      int d[2][4] = {0, 1, 2, 3, 4, 5, 6, 7};
     rather than this
      int d[2][4] = {0, 4, 1, 5, 2, 6, 3, 7};
                                          Happy to help…!
                                                                11
Multidimensional arrays as
parameters
 Only the first subscript may be left unspecified
void f(int matrix[][10]);         /* OK */
void g(int (*matrix)[10]);        /* OK */
void h(int matrix[][]);           /* not OK */
 Why?
   Because the other sizes are needed for scaling when
    evaluating subscript expressions (see slide 10)
   This points out an important drawback to C:
    Arrays do not carry information about their own sizes!
    If array size is needed, you must supply it somehow
    (e.g., when passing an array argument, you often have
    to pass an additional “array size” argument) – bummer

                                                 Happy to help…!   12

More Related Content

What's hot

Lec2&3 data structure
Lec2&3 data structureLec2&3 data structure
Lec2&3 data structureSaad Gabr
 
Computer Programming- Lecture 5
Computer Programming- Lecture 5 Computer Programming- Lecture 5
Computer Programming- Lecture 5
Dr. Md. Shohel Sayeed
 
Very interesting C programming Technical Questions
Very interesting C programming Technical Questions Very interesting C programming Technical Questions
Very interesting C programming Technical Questions
Vanathi24
 
Lecture 8
Lecture 8Lecture 8
Lecture 8
Mohammed Saleh
 
Pointers
PointersPointers
Pointers
PreethyJemima
 
Lecture 17 - Strings
Lecture 17 - StringsLecture 17 - Strings
Lecture 17 - Strings
Md. Imran Hossain Showrov
 
Pointers & References in C++
Pointers & References in C++Pointers & References in C++
Pointers & References in C++
Ilio Catallo
 
Lec 38.39 - pointers
Lec 38.39 -  pointersLec 38.39 -  pointers
Lec 38.39 - pointersPrincess Sam
 
Arrays in c
Arrays in cArrays in c
Arrays in c
CHANDAN KUMAR
 
Lecture 12: Classes and Files
Lecture 12: Classes and FilesLecture 12: Classes and Files
Lecture 12: Classes and Files
Dr. Md. Shohel Sayeed
 
Computer Programming- Lecture 6
Computer Programming- Lecture 6Computer Programming- Lecture 6
Computer Programming- Lecture 6
Dr. Md. Shohel Sayeed
 
C programming - Pointers
C programming - PointersC programming - Pointers
C programming - Pointers
Wingston
 
Pointers in c
Pointers in cPointers in c
Pointers in c
CHANDAN KUMAR
 
Computer Programming- Lecture 9
Computer Programming- Lecture 9Computer Programming- Lecture 9
Computer Programming- Lecture 9
Dr. Md. Shohel Sayeed
 
Monoids - Part 2 - with examples using Scalaz and Cats
Monoids - Part 2 - with examples using Scalaz and CatsMonoids - Part 2 - with examples using Scalaz and Cats
Monoids - Part 2 - with examples using Scalaz and Cats
Philip Schwarz
 

What's hot (20)

Lec2&3_DataStructure
Lec2&3_DataStructureLec2&3_DataStructure
Lec2&3_DataStructure
 
Lec2&3 data structure
Lec2&3 data structureLec2&3 data structure
Lec2&3 data structure
 
javaarray
javaarrayjavaarray
javaarray
 
Computer Programming- Lecture 5
Computer Programming- Lecture 5 Computer Programming- Lecture 5
Computer Programming- Lecture 5
 
Very interesting C programming Technical Questions
Very interesting C programming Technical Questions Very interesting C programming Technical Questions
Very interesting C programming Technical Questions
 
Lecture 8
Lecture 8Lecture 8
Lecture 8
 
Pointers in C
Pointers in CPointers in C
Pointers in C
 
Pointers
PointersPointers
Pointers
 
Lecture 17 - Strings
Lecture 17 - StringsLecture 17 - Strings
Lecture 17 - Strings
 
Pointers & References in C++
Pointers & References in C++Pointers & References in C++
Pointers & References in C++
 
Nn
NnNn
Nn
 
Lec 38.39 - pointers
Lec 38.39 -  pointersLec 38.39 -  pointers
Lec 38.39 - pointers
 
Lec 37 - pointers
Lec 37 -  pointersLec 37 -  pointers
Lec 37 - pointers
 
Arrays in c
Arrays in cArrays in c
Arrays in c
 
Lecture 12: Classes and Files
Lecture 12: Classes and FilesLecture 12: Classes and Files
Lecture 12: Classes and Files
 
Computer Programming- Lecture 6
Computer Programming- Lecture 6Computer Programming- Lecture 6
Computer Programming- Lecture 6
 
C programming - Pointers
C programming - PointersC programming - Pointers
C programming - Pointers
 
Pointers in c
Pointers in cPointers in c
Pointers in c
 
Computer Programming- Lecture 9
Computer Programming- Lecture 9Computer Programming- Lecture 9
Computer Programming- Lecture 9
 
Monoids - Part 2 - with examples using Scalaz and Cats
Monoids - Part 2 - with examples using Scalaz and CatsMonoids - Part 2 - with examples using Scalaz and Cats
Monoids - Part 2 - with examples using Scalaz and Cats
 

Similar to Array

Arrays
ArraysArrays
Multidimensional arrays in C++
Multidimensional arrays in C++Multidimensional arrays in C++
Multidimensional arrays in C++
Ilio Catallo
 
Numpy Talk at SIAM
Numpy Talk at SIAMNumpy Talk at SIAM
Numpy Talk at SIAM
Enthought, Inc.
 
Array
ArrayArray
ch08.ppt
ch08.pptch08.ppt
ch08.ppt
NewsMogul
 
C Programming - Refresher - Part III
C Programming - Refresher - Part IIIC Programming - Refresher - Part III
C Programming - Refresher - Part III
Emertxe Information Technologies Pvt Ltd
 
ESC112 Course lecture slides on pointers and memory allocation.pptx
ESC112 Course lecture slides on pointers and memory allocation.pptxESC112 Course lecture slides on pointers and memory allocation.pptx
ESC112 Course lecture slides on pointers and memory allocation.pptx
krishna50blogging
 
Pointers_c
Pointers_cPointers_c
Pointers_c
ahmed safwat
 
Python Programming for basic beginners.pptx
Python Programming for basic beginners.pptxPython Programming for basic beginners.pptx
Python Programming for basic beginners.pptx
mohitesoham12
 
Thinking Functionally In Ruby
Thinking Functionally In RubyThinking Functionally In Ruby
Thinking Functionally In RubyRoss Lawley
 
Python Datatypes by SujithKumar
Python Datatypes by SujithKumarPython Datatypes by SujithKumar
Python Datatypes by SujithKumar
Sujith Kumar
 
Python Session - 3
Python Session - 3Python Session - 3
Python Session - 3
AnirudhaGaikwad4
 
Session 4
Session 4Session 4
C (PPS)Programming for problem solving.pptx
C (PPS)Programming for problem solving.pptxC (PPS)Programming for problem solving.pptx
C (PPS)Programming for problem solving.pptx
rohinitalekar1
 
CodeFest 2010. Иноземцев И. — Fantom. Cross-VM Language
CodeFest 2010. Иноземцев И. — Fantom. Cross-VM LanguageCodeFest 2010. Иноземцев И. — Fantom. Cross-VM Language
CodeFest 2010. Иноземцев И. — Fantom. Cross-VM LanguageCodeFest
 
รายงานคอม
รายงานคอมรายงานคอม
รายงานคอมAreeya Onnom
 
รายงานคอม
รายงานคอมรายงานคอม
รายงานคอมAreeya Onnom
 
Arrays and structures
Arrays and structuresArrays and structures
Arrays and structuresMohd Arif
 

Similar to Array (20)

Arrays
ArraysArrays
Arrays
 
Multidimensional arrays in C++
Multidimensional arrays in C++Multidimensional arrays in C++
Multidimensional arrays in C++
 
Numpy Talk at SIAM
Numpy Talk at SIAMNumpy Talk at SIAM
Numpy Talk at SIAM
 
Array
ArrayArray
Array
 
ch08.ppt
ch08.pptch08.ppt
ch08.ppt
 
C Programming - Refresher - Part III
C Programming - Refresher - Part IIIC Programming - Refresher - Part III
C Programming - Refresher - Part III
 
ESC112 Course lecture slides on pointers and memory allocation.pptx
ESC112 Course lecture slides on pointers and memory allocation.pptxESC112 Course lecture slides on pointers and memory allocation.pptx
ESC112 Course lecture slides on pointers and memory allocation.pptx
 
Pointers_c
Pointers_cPointers_c
Pointers_c
 
2ds
2ds2ds
2ds
 
Python Programming for basic beginners.pptx
Python Programming for basic beginners.pptxPython Programming for basic beginners.pptx
Python Programming for basic beginners.pptx
 
Thinking Functionally In Ruby
Thinking Functionally In RubyThinking Functionally In Ruby
Thinking Functionally In Ruby
 
Python Datatypes by SujithKumar
Python Datatypes by SujithKumarPython Datatypes by SujithKumar
Python Datatypes by SujithKumar
 
Python Session - 3
Python Session - 3Python Session - 3
Python Session - 3
 
Session 4
Session 4Session 4
Session 4
 
C (PPS)Programming for problem solving.pptx
C (PPS)Programming for problem solving.pptxC (PPS)Programming for problem solving.pptx
C (PPS)Programming for problem solving.pptx
 
array2d.ppt
array2d.pptarray2d.ppt
array2d.ppt
 
CodeFest 2010. Иноземцев И. — Fantom. Cross-VM Language
CodeFest 2010. Иноземцев И. — Fantom. Cross-VM LanguageCodeFest 2010. Иноземцев И. — Fantom. Cross-VM Language
CodeFest 2010. Иноземцев И. — Fantom. Cross-VM Language
 
รายงานคอม
รายงานคอมรายงานคอม
รายงานคอม
 
รายงานคอม
รายงานคอมรายงานคอม
รายงานคอม
 
Arrays and structures
Arrays and structuresArrays and structures
Arrays and structures
 

More from Mayank Saxena

Financial services marketing
Financial services marketingFinancial services marketing
Financial services marketingMayank Saxena
 
Introduction to financial service
Introduction to financial serviceIntroduction to financial service
Introduction to financial serviceMayank Saxena
 
Artificial intelligence
Artificial intelligenceArtificial intelligence
Artificial intelligenceMayank Saxena
 
artificial intelligence
artificial intelligenceartificial intelligence
artificial intelligenceMayank Saxena
 
Wi-fi (ppt) by Mayank Saxena
Wi-fi (ppt) by Mayank SaxenaWi-fi (ppt) by Mayank Saxena
Wi-fi (ppt) by Mayank Saxena
Mayank Saxena
 

More from Mayank Saxena (19)

operating system
operating systemoperating system
operating system
 
operating system
operating systemoperating system
operating system
 
Financial services marketing
Financial services marketingFinancial services marketing
Financial services marketing
 
Introduction to financial service
Introduction to financial serviceIntroduction to financial service
Introduction to financial service
 
il&fs investmart
 il&fs investmart il&fs investmart
il&fs investmart
 
financial services
financial servicesfinancial services
financial services
 
Html tutorial.02
Html tutorial.02Html tutorial.02
Html tutorial.02
 
Introduction html
Introduction htmlIntroduction html
Introduction html
 
Steganography
SteganographySteganography
Steganography
 
Silc
SilcSilc
Silc
 
Artificial intelligence
Artificial intelligenceArtificial intelligence
Artificial intelligence
 
Vlan
VlanVlan
Vlan
 
Cloud computing (2)
Cloud computing (2)Cloud computing (2)
Cloud computing (2)
 
Silc
SilcSilc
Silc
 
Wi fi
Wi fiWi fi
Wi fi
 
Cloud computing
Cloud computingCloud computing
Cloud computing
 
artificial intelligence
artificial intelligenceartificial intelligence
artificial intelligence
 
4 g world
4 g world4 g world
4 g world
 
Wi-fi (ppt) by Mayank Saxena
Wi-fi (ppt) by Mayank SaxenaWi-fi (ppt) by Mayank Saxena
Wi-fi (ppt) by Mayank Saxena
 

Array

  • 1. By- mynk Happy to help…! 1
  • 2. Review of arrays  There are no array variables in C – only array names  Each name refers to a constant pointer  Space for array elements is allocated at declaration time  Can’t change where the array name refers to…  but you can change the array elements, via pointer arithmetic ??? ??? ??? ??? (int []) (int) (int) (int) (int) m int m[4]; Happy to help…! 2
  • 3. Subscripts and pointer arithmetic  array[subscript] equivalent to *(array + (subscript))  Strange but true: Given earlier declaration of m, the expression 2[m] is legal!  Not only that: it’s equivalent to *(2+m) *(m+2) m[2] Happy to help…! 3
  • 4. Array names and pointer variables, ??? ??? ??? playing together int m[3]; subscript OK (int []) (int) (int) (int) with pointer variable m (int []) int *mid = m + 1; mid (int []) right int *right = mid[1]; (int []) left int *left = mid[-1]; (int []) compiler may not catch this – beyond int *beyond = mid[2]; environment certainly won’t runtime Happy to help…! 4
  • 5. Array names as function arguments  In C, arguments are passed “by value”  A temporary copy of each argument is created, solely for use within the function call void f(int x, int *y) { … } void g(…) { 17 42 17 int a = 17, b = 42; (int) (int) (int) (int []) f(a, &b); a b x y … } g f  Pass-by-value is “safe” in that the function plays only in its “sandbox” of temporary variables –  can’t alter the values of variables in the callee (except via the return value) Happy to help…! 5
  • 6. Array names as function arguments  But, functions that take arrays as arguments can exhibit what looks like “pass-by-reference” behavior, where the array passed in by the callee does get changed  Remember the special status of arrays in C – They are basically just pointers.  So arrays are indeed passed by value – but only the pointer is copied, not the array elements!  Note the advantage in efficiency (avoids a lot of copying)  But – the pointer copy points to the same elements as the callee’s array  These elements can easily be modified via pointer manipulation Happy to help…! 6
  • 7. Array names as function arguments  The strcpy “string copy” function puts this “pseudo” call-by-reference behavior to good use void strcpy(char *buffer, char const *string); void f(…) { char original[4] = ″dog″; g d o NUL (char []) (char []) char copy[4]; (char) (char) (char) (char) origin string strcpy(copy, original); al } (char []) d ??? o ??? g ??? NUL ??? (char []) (char) (char) (char) (char) copy buffer f strcpy Happy to help…! 7
  • 8. When can array size be omitted?  There are a couple of contexts in which an array declaration need not have a size specified:  Parameter declaration: int strlen(char string[]);  As we’ve seen, the elements of the array argument are not copied, so the function doesn’t need to know how many elements there are.  Array initialization: int vector[] = {1, 2, 3, 4, 5};  In this case, just enough space is allocated to fit all (five) elements of the initializer list Happy to help…! 8
  • 9. Multidimensional arrays  How to interpret a declaration like: int d[2][4];  This is an array with two elements:  Each element is an array of four int values  The elements are laid out sequentially in memory, just like a one-dimensional array Row-major order: the(int) elements of the rightmost (int) (int)  (int) (int) (int) (int) (int) subscript are stored contiguously d[0][1] d[1][2] d[1][3] d[0][0] d[0][2] d[0][3] d[1][0] d[1][1] d[0] d[1] Happy to help…! 9
  • 10. Subscripting in a multidimensional array int d[2][4]; *(d+1) [1] *(*(d+1)+2) [2] d Then increment by the size of 2 ints Increment by the size of 1 array of 4 ints (int) (int) (int) (int) (int) (int) (int) (int) d[0][0] d[0][1] d[0][2] d[0][3] d[1][0] d[1][1] d[1][2] d[1][3] d[0] d[1] Happy to help…! 10
  • 11. Why do we care about storage order?  If you keep within the “paradigm” of the multidimensional array, the order doesn’t matter…  But if you use tricks with pointer arithmetic, it matters a lot 0 1 2 3  It also matters for initialization 4 5 6 7  To initialize d like this:  use this: int d[2][4] = {0, 1, 2, 3, 4, 5, 6, 7};  rather than this int d[2][4] = {0, 4, 1, 5, 2, 6, 3, 7}; Happy to help…! 11
  • 12. Multidimensional arrays as parameters  Only the first subscript may be left unspecified void f(int matrix[][10]); /* OK */ void g(int (*matrix)[10]); /* OK */ void h(int matrix[][]); /* not OK */  Why?  Because the other sizes are needed for scaling when evaluating subscript expressions (see slide 10)  This points out an important drawback to C: Arrays do not carry information about their own sizes! If array size is needed, you must supply it somehow (e.g., when passing an array argument, you often have to pass an additional “array size” argument) – bummer Happy to help…! 12