Arrays in C (with a brief Introduction to Pointers) - PowerPoint PPT Presentation

About This Presentation
Title:

Arrays in C (with a brief Introduction to Pointers)

Description:

double 8 bytes (Almost) always aligned to multiple of size in bytes ... Construct a pointer to a double that is n doubles beyond *p, and assign it to r ... – PowerPoint PPT presentation

Number of Views:46
Avg rating:3.0/5.0
Slides: 45
Provided by: hughc7
Category:

less

Transcript and Presenter's Notes

Title: Arrays in C (with a brief Introduction to Pointers)


1
Arrays in C(with a brief Introduction to
Pointers)
  • CS-2301, System Programming for Non-majors
  • (Slides include materials from The C Programming
    Language, 2nd ed., by Kernighan and Ritchie and
    from C How to Program, 5th ed., by Deitel and
    Deitel)

2
Reading Assignment
  • Chapter 5 of Kernighan Ritchie

3
Definition Array
  • A collection of objects of the same type stored
    contiguously in memory under one name
  • May be type of any kind of variable
  • May even be collection of arrays!
  • For ease of access to any member of array
  • For passing to functions as a group

4
Examples
  • int A10
  • An array of ten integers
  • A0, A1, , A9
  • double B20
  • An array of twenty long floating point numbers
  • B0, B1, , B19
  • Arrays of structs, unions, pointers, etc., are
    also allowed

5
Examples
  • int A10
  • An array of ten integers
  • A0, A1, , A9
  • double B20
  • An array of twenty long floating point numbers
  • B0, B1, , B19
  • Arrays of structs, unions, pointers, etc., are
    also allowed
  • Array indexes always start at zero in C

6
Examples (continued)
  • int C
  • An array of an unknown number of integers
    (allowable in a parameter)
  • C0, C1, , Cmax-1
  • int D1020
  • An array of ten rows, each of which is an array
    of twenty integers
  • D00, D01, , D10, D11, ,
    D919
  • Not used so often as arrays of pointers

7
Array Element
  • May be used wherever a variable of the same type
    may be used
  • Examples
  • A3 x y
  • x y A3
  • z sin(Ai) cos(Bj)

8
Array Elements (continued)
  • Generic form
  • ArrayNameinteger-expression
  • ArrayNameinteger-expression integer-expression
  • Has the same type as the underlying type of the
    array
  • May be used on left or right of assignment
  • May be used in any expression
  • Definition array index the expression between
    the square brackets

9
Array Elements (continued)
  • Array elements are most commonly used in loops
  • E.g.,
  • for(i0 i lt max i)Ai ii
  • sum 0 for(j0 j lt max j)sum Bj
  • for (count0rc!EOFcount)rcscanf(f,
    Acount)

10
Caution! Caution! Caution!
  • It is the programmers responsibility to avoid
    indexing off the end of an array
  • Likely to corrupt data
  • May cause a segmentation fault
  • Could expose system to a security hole!
  • C does NOT check array bounds
  • I.e., whether index points to an element within
    the array
  • Might be high (beyond the end) or negative
    (before the array starts)

11
Caution! Caution! Caution!
  • It is the programmers responsibility to avoid
    indexing off the end of an array
  • Likely to corrupt data
  • May cause a segmentation fault
  • Could expose system to a security hole!
  • C does NOT check array bounds
  • I.e., whether index points to an element within
    the array
  • Might be high (beyond the end) or negative
    (before the array starts)

12
Questions
13
Declaring Arrays
  • Static or automatic
  • Array size determined explicitly or implicitly
  • Array size may be determined at run-time
  • Automatic only
  • Not in textbook

14
Declaring Arrays (continued)
  • Outside of any function always static
  • int A13
  • define CLASS_SIZE 73
  • double BCLASS_SIZE
  • const int nElements 25
  • float CnElements
  • static char256 /not visible to linker /

15
Declaring Arrays (continued)
  • Outside of any function always static
  • int A13
  • define CLASS_SIZE 73
  • double BCLASS_SIZE
  • const int nElements 25
  • float CnElements
  • static char256 /not visible to linker /

Static ? retains values across function calls
16
Static Data Allocation
17
Declaring Arrays (continued)
  • Inside function or compound statement usually
    automatic
  • void f( )
  • int A13
  • define CLASS_SIZE 73
  • double BCLASS_SIZE
  • const int nElements 25
  • float CnElements
  • static char D256 /static, not visible outside
    function /
  • //f

18
Static Data Allocation
19
Declaring Arrays (continued)
  • Inside function or compound statement usually
    automatic
  • void f( )
  • int A13
  • define CLASS_SIZE 73
  • double BCLASS_SIZE
  • const int nElements 25
  • float CnElements
  • static char D256 /static, not visible outside
    function /
  • //f

20
Dynamic Array Size Determination
  • gcc supports the following
  • void func(const int n) double Array2n
  • //func
  • I.e., array size is determined by evaluating an
    expression at run-time
  • Automatic allocation on The Stack
  • Not in C88 ANSI standard, not in Kernighan
    Ritchie
  • Part of C99

21
Array Initialization
  • int A5 2, 4, 8, 16, 32
  • Static or automatic
  • int B20 2, 4, 8, 16, 32
  • Unspecified elements are guaranteed to be zero
  • int C4 2, 4, 8, 16, 32
  • Error compiler can detect too many initial
    values
  • int D5 2n, 4n, 8n, 16n, 32n
  • Automatically only array initialized to
    expressions
  • int En 1
  • Dynamically allocated array (automatic only).
    Zeroth element initialized to 1 all other
    elements initialized to 0

22
Implicit Array Size Determination
  • int days 31, 28, 31, 30, 31, 30, 31, 31, 30,
    31, 30, 31
  • Array is created with as many elements as initial
    values
  • In this case, 12 elements
  • Values must be compile-time constants (for static
    arrays)
  • Values may be run-time expressions (for automatic
    arrays)
  • See p. 86

23
Getting Size of Implicit Array
  • sizeof operator returns of bytes of memory
    required by operand
  • See p.135
  • Examples
  • sizeof (int) of bytes per int
  • sizeof (float) of bytes per float
  • sizeof days of bytes in array days (previous
    slide)
  • of elements in days (sizeof days)/sizeof(int)
  • Must be able to be determined at compile time
  • Dynamically allocated arrays not supported

24
Questions?
25
Digression Memory Organization
  • All modern processors have memories organized as
    sequence of numbered bytes
  • Many (but not all) are linear sequences
  • Notable exception Pentium!
  • Definitions
  • Byte an 8-bit memory cell capable of storing a
    value in range 0 255
  • Address the number of a memory cell

26
Memory Organization (continued)
  • Larger data types are sequences of bytes e.g.,
  • short int 2 bytes
  • int 2 or 4 bytes
  • long 4 or 8 bytes
  • float 4 bytes
  • double 8 bytes
  • (Almost) always aligned to multiple of size in
    bytes
  • Address is first byte of sequence (i.e., byte
    zero)
  • May be low-order or high-order byte
  • Big endian or Little endian

27
Definition Pointer
11
  • A value indicating the number of (the first byte
    of) a data object
  • Also called an Address
  • Used in machine language to identify which data
    to access
  • E.g., stack pointer is address of most recent
    entry of The Stack
  • Usually 2, 4, or 8 bytes, depending upon machine
    architecture

28
Memory Addressing
29
Pointers in C
  • Used everywhere
  • For building useful, interesting, data structures
  • For returning data from functions
  • For managing arrays
  • operator generates a pointer to x
  • E.g., scanf(d, x)
  • E.g., p c
  • Operand of must be an l-value a legal
    object on left of assignment operator ()
  • Unary operator dereferences a pointer
  • i.e., gets value pointed to
  • E.g. p refers to value of c (above)
  • E.g., p x y p q

30
Declaring Pointers in C
  • int p a pointer to an int
  • double q a pointer to a double
  • char r a pointer to a pointer to a char
  • type s a pointer to an object of type
    type
  • E.g, a struct, union, function, something defined
    by a typedef, etc.

31
Declaring Pointers in C (continued)
  • Pointer declarationsread from right to left
  • const int p
  • p is a pointer to an integer constant
  • I.e., pointer can change, thing it points to
    cannot
  • int const q
  • q is a constant pointer to an integer variable
  • const int const r
  • r is a constant pointer to an integer constant

32
Pointer Arithmetic
  • int p, qq p 1
  • Construct a pointer to the next integer after p
    and assign it to q
  • double p, rint nr p n
  • Construct a pointer to a double that is n doubles
    beyond p, and assign it to r
  • n may be negative

33
Pointer Arithmetic (continued)
  • long int p, qp q--
  • Increment p to point to the next long int
    decrement q to point to the previous long int
  • float p, qint nn p q
  • n is the number of floats between p and q
    i.e., what would be added to q to get p

34
Pointer Arithmetic (continued)
  • long int p, qp q--
  • Increment p to point to the next long int
    decrement q to point to the previous long int
  • float p, qint nn p q
  • n is the number of floats between p and q
    i.e., what would be added to q to get p

35
Why introduce pointers in the middle of a lesson
on arrays?
  • Arrays and pointers are closely related in C
  • In fact, they are essentially the same thing!
  • Esp. when used as parameters of functions
  • int A10int p
  • Type of A is int
  • p A and A p are legal assignments
  • p refers to A0p n refers to An
  • p A5 is the same as p A 5

36
Arrays and Pointers (continued)
  • double A10double p
  • Only difference
  • double A10 sets aside ten units of memory, each
    large enough to hold a double
  • double p sets aside one pointer-sized unit of
    memory
  • Note all pointer variables are the same size in
    any given machine architecture
  • Regardless of what types they point to

37
Note
  • C does not assign arrays to each other
  • E.g,
  • double A10double B10A B
  • assigns the pointer value B to the pointer value
    A
  • Contents of array A are untouched

38
Arrays as Function Parameters
  • void init(float A, int arraySize)void
    init(float A, int arraySize)
  • Are identical function prototypes!
  • Pointer is passed by value
  • I.e. caller copies the value of a pointer to
    float to the parameter
  • Called function can reference through that
    pointer to reach thing pointed to

39
Arrays as Function Parameters (continued)
  • void init(float A, int arraySize) int
    n for(n 0 n lt arraySize n) An
    (float)n //init
  • Assigns values to the array A in place
  • So that caller can see the changes!

40
Examples
  • while ((rc scanf("lf", arraycount)) !EOF
    rc0)
  • double getLargest(const double A, const int
    sizeA)
  • d getLargest(A1, sizeA-1)

41
Result
  • Even though all arguments are passed by value to
    functions
  • pointers allow functions to assign back to data
    of caller
  • Arrays are pointers passed by value

42
Safety Note
  • When passing arrays to functions, always specify
    const if you dont want function changing the
    value of any elements
  • Reason you dont know whether your function
    would pass array to another before returning to
    you
  • Exception many software packages dont specify
    const in their own headers, so you cant either!

43
Reading Assignment
  • Chapter 5 of Kernighan Ritchie

44
Questions?
Write a Comment
User Comments (0)
About PowerShow.com