03 Arrays Pointers

Embed Size (px)

DESCRIPTION

c

Citation preview

  • Arrays and Pointers in C

    Arrays and Pointers

  • ObjectivesBe able to use arrays, pointers, and strings in C programs

    Be able to explain the representation of these data types at the machine level, including their similarities and differences CoxArrays and Pointers*

    Arrays and Pointers

  • CoxArrays and Pointers*Arrays in CNo bounds checking!Allowed usually causes no errorarray[10] may overwrite bUnlike Java, array size in declarationint array[10];int b;

    array[0] = 3;array[9] = 4;array[10] = 5;array[-1] = 6;All elements of same type homogenousFirst element (index 0)Last element (index size - 1)

    Arrays and Pointers

  • CoxArrays and Pointers*Array RepresentationHomogeneous Each element same size s bytesAn array of m data values is a sequence of ms bytesIndexing: 0th value at byte s0, 1st value at byte s1,

    m and s are not part of representationUnlike in some other languagess known by compiler usually irrelevant to programmerm often known by compiler if not, must be saved by programmerint a[3];

    Arrays and Pointers

  • CoxArrays and Pointers*Array Representationchar c1;int a[3];char c2;int i;Could be optimized by making these adjacent, and reducing padding (by default, not)Array aligned bysize of elements

    Arrays and Pointers

  • CoxArrays and Pointers*Array Sizes

    What is

    sizeof(array[3])?

    sizeof(array)?int array[10];440returns the size of an object in bytes

    Arrays and Pointers

  • CoxArrays and Pointers*Multi-Dimensional Arraysint matrix[2][3];

    matrix[1][0] = 17;Recall: no bounds checking

    What happens when you write:

    matrix[0][3] = 42;Row MajorOrganization

    Arrays and Pointers

  • CoxArrays and Pointers*Variable-Length Arraysintfunction(int n){ int array[n]; New C99 feature: Variable-length arraysdefined within functions

    Global arrays must still have fixed (constant) length

    Arrays and Pointers

  • CoxArrays and Pointers*Memory AddressesStorage cells are typically viewed as being byte-sizedUsually the smallest addressable unit of memoryFew machines can directly address bits individuallySuch addresses are sometimes called byte-addressesMemory is often accessed as wordsUsually a word is the largest unit of memory access by a single machine instructionCLEARs word size is 8 bytes (= sizeof(long))A word-address is simply the byte-address of the words first byte

    Arrays and Pointers

  • CoxArrays and Pointers*Pointers

    Special case of bounded-size natural numbersMaximum memory limited by processor word-size232 bytes = 4GB, 264 bytes = 16 exabytes

    A pointer is just another kind of valueA basic type in C

    int *ptr;The variable ptr is a pointer to an int.

    Arrays and Pointers

  • CoxArrays and Pointers*Pointer Operations in CCreation& variableReturns variables memory addressDereference* pointerReturns contents stored at addressIndirect assignment* pointer = valStores value at address

    Of course, still have...

    Assignmentpointer = ptrStores pointer in another variable

    Arrays and Pointers

  • CoxArrays and Pointers*Using Pointersint i1;int i2;int *ptr1;int *ptr2;

    i1 = 1;i2 = 2;

    ptr1 = &i1;ptr2 = ptr1;

    *ptr1 = 3;i2 = *ptr2;120x10000x100033

    Arrays and Pointers

  • CoxArrays and Pointers*Using Pointers (cont.)Type check warning: int_ptr2 is not an intint1 becomes 8int int1 = 1036; /* some data to point to */int int2 = 8;

    int *int_ptr1 = &int1; /* get addresses of data */int *int_ptr2 = &int2;

    *int_ptr1 = int_ptr2;

    *int_ptr1 = int2;What happens?

    Arrays and Pointers

  • CoxArrays and Pointers*Using Pointers (cont.)Type check warning: *int_ptr2 is not an int *Changes int_ptr1 doesnt change int1int int1 = 1036; /* some data to point to */int int2 = 8;

    int *int_ptr1 = &int1; /* get addresses of data */int *int_ptr2 = &int2;

    int_ptr1 = *int_ptr2;

    int_ptr1 = int_ptr2;What happens?

    Arrays and Pointers

  • CoxArrays and Pointers*Pointer Arithmeticpointer + numberpointer number

    E.g., pointer + 1 adds 1 something to a pointerIn each, p now points to b(Assuming compiler doesnt reorder variables in memory)Adds 1*sizeof(char) to the memory addressAdds 1*sizeof(int) to the memory addressPointer arithmetic should be used cautiously

    Arrays and Pointers

  • CoxArrays and Pointers*The Simplest Pointer in C

    Special constant pointer NULLPoints to no dataDereferencing illegal causes segmentation fault

    To define, include or

    Arrays and Pointers

  • CoxArrays and Pointers*Generic Pointersvoid *: a pointer to anything

    Lose all information about what type of thing is pointed to Reduces effectiveness of compilers type-checking Cant use pointer arithmeticvoid *p;int i;char c;p = &i;p = &c;putchar(*(char *)p);type cast: tells the compiler to change an objects type (for type checking purposes does not modify the object in any way)

    Dangerous! Sometimes necessary

    Arrays and Pointers

  • CoxArrays and Pointers*Pass-by-Referencevoidset_x_and_y(int *x, int *y){ *x = 1001; *y = 1002;}

    voidf(void){ int a = 1; int b = 2; set_x_and_y(&a,&b);}

    Arrays and Pointers

  • CoxArrays and Pointers*Arrays and PointersDirty secret:Array pointer to the initial (0th) array element

    a[i] *(a+i)

    An array is passed to a function as a pointerThe array size is lost!

    Usually bad style to interchange arrays and pointersAvoid pointer arithmetic!Really int *arrayint foo(int array[], unsigned int size){ array[size - 1] }

    intmain(void){ int a[10], b[5]; foo(a, 10) foo(b, 5) }Must explicitlypass the sizePassing arrays:

    Arrays and Pointers

  • CoxArrays and Pointers*Arrays and Pointersint foo(int array[], unsigned int size){ printf(%d\n, sizeof(array));}

    intmain(void){ int a[10], b[5]; foo(a, 10) foo(b, 5) printf(%d\n, sizeof(a));}What does this print?What does this print?840... because array is reallya pointer

    Arrays and Pointers

  • CoxArrays and Pointers*Arrays and Pointersint i;int array[10];

    for (i = 0; i < 10; i++){ array[i] = ;}int *p;int array[10];

    for (p = array; p < &array[10]; p++){ *p = ;}These two blocks of code are functionally equivalent

    Arrays and Pointers

  • CoxArrays and Pointers*StringsIn C, strings are just an array of charactersTerminated with \0 characterArrays for bounded-length stringsPointer for constant strings (or unknown length)char str1[15] = Hello, world!\n;char *str2 = Hello, world!\n;Hello,wlord!\nlengthHello,wlord!\nterminatorPascal, Java, C, C terminator: \0

    Arrays and Pointers

  • CoxArrays and Pointers*String lengthMust calculate length:

    Provided by standard C library: #include intstrlen(char str[]){ int len = 0;

    while (str[len] != \0) len++;

    return (len);} can pass anarray or pointerCheck for terminatorarray access to pointer!What is the size of the array???

    Arrays and Pointers

  • Pointer to Pointer (char **argv)CoxArrays and Pointers*Passing arguments to main:intmain(int argc, char **argv){ ...} Suppose you run the program this way

    UNIX% ./program hello 1 2 3

    argc == 5 (five strings on the command line)

    Arrays and Pointers

  • CoxArrays and Pointers*char **argvargv[0]argv[1]argv[2]0x10000x10080x1010argv[3]argv[4]0x10180x1020./programhello123These are strings!!Not integers!

    Arrays and Pointers

  • CoxArrays and Pointers*Next TimeStructures and Unions

    Arrays and Pointers

    *