chapter 9 - arrays and pointers
DESCRIPTION
Chapter 9 - Arrays and Pointers. CS 124. Learning Objectives…. After completing this section, you should be able to Explain what an interrupt is. Write an Interrupt Service Routine ( ISR’s). Use the Watchdog as a limited feature timer. Discuss the computer energy consumption issues. - PowerPoint PPT PresentationTRANSCRIPT
S08: Arrays and Pointers
Required: PM: Ch 6.5, pgs 73-75Arrays
Pointer Basics Pointer Tutorial (Chps 1-4)
Recommended: K&R, Chapter 5
BYU CS 224 Pointers and Arrays 2
CS 224Chapter Project Homework
S00: IntroductionUnit 1: Digital Logic
S01: Data TypesS02: Digital Logic
L01: Warm-upL02: FSM
HW01HW02
Unit 2: ISAS03: ISAS04: MicroarchitectureS05: Stacks / InterruptsS06: Assembly
L03: BlinkyL04: MicroarchL05b: Traffic LightL06a: Morse Code
HW03HW04HW05HW06
Unit 3: CS07: C LanguageS08: PointersS09: StructsS10: I/O
L07b: Morse IIL08a: LifeL09a: Pong
HW07HW08HW09HW10
Pointers and Arrays 3BYU CS 224
Learning Objectives…
Students will be able to: Deal with limited system resources (time and memory). Parse a RLE string for tokens. Write time critical algorithms. Examine compiler generated code and optimize the code
for speed. Use C bit-arrays and pointers. Develop techniques unique to computer simulations.
Pointers and Arrays 4BYU CS 224
Topics… Arrays C Strings Array Arguments Pointers Null Pointers Pointer Arithmetic Arrays and Pointers Static Variables Parsing C I/O Pointers to Pointers Multi-dimensional Arrays Command-line Arguments
Pointers and Arrays 5BYU CS 224
Arrays An array is a sequence (in memory) of like items. Arrays are NOT data types. Arrays must be declared before they are used.
General form:type variable-name[number_of_elements];
The array size must be explicit at compile time – needed to reserve memory space
Array elements individually accessed with index. General form:
variable-name[index]; Zero based subscripts No compile-time or run-time limit checking
Arrays
Pointers and Arrays 6BYU CS 224
Initialization of Arrays Elements can be initialized when they are declared in the
same way as ordinary variables. type array_name[size] = { list of values separated by commas }; int number[3] = {0, 0, 0};
Unspecified elements will be set to zero automatically. Array declarations may omit the size.
int counter[] = {1, 1, 1, 1}; char RGB_image[][3] = { {255,0,255}, {0,255,0}};
Global variables Zeroed before main is called (***NOT WITH CCS***)
Problems with C initialization of arrays No convenient way to initialize selected elements. No shortcut to initialize large number of elements.
Arrays
Pointers and Arrays 7BYU CS 224
Local Array Exampleint main(){ int array[10]; int x; for (x = 0; x < 10; x++) { array[x] = x; } return 0;}
main:0x8040: 8031 0016 SUB.W #0x0016,SP0x8044: 4381 0014 CLR.W 0x0014(SP)0x8048: 90B1 000A 0014 CMP.W #0x000a,0x0014(SP)0x804e: 340D JGE (C$DW$L$main$2$E) C$DW$L$main$2$B, C$L1:0x8050: 411F 0014 MOV.W 0x0014(SP),R150x8054: 5F0F RLA.W R150x8056: 510F ADD.W SP,R150x8058: 419F 0014 0000 MOV.W 0x0014(SP),0x0000(R15)0x805e: 5391 0014 INC.W 0x0014(SP)0x8062: 90B1 000A 0014 CMP.W #0x000a,0x0014(SP)0x8068: 3BF3 JL (C$L1) C$L2, C$DW$L$main$2$E:0x806a: 430C CLR.W R120x806c: 5031 0016 ADD.W #0x0016,SP0x8070: 4130 RET
Arrays
x 0x0014(SP)array[9] 0x0012(SP)array[8] 0x0010(SP)array[7] 0x000e(SP)array[6] 0x000c(SP)array[5] 0x000a(SP)array[4] 0x0008(SP)array[3] 0x0006(SP)array[2] 0x0004(SP)array[1] 0x0002(SP)array[0] 0x0000(SP)
SP
SP
Pointers and Arrays 8BYU CS 224
Global Array Example
int array[10];int x;int main(){ for (x = 0; x < 10; x++) { array[x] = x; } return 0;}
main:0x806a: 4382 0214 CLR.W &x0x806e: 90B2 000A 0214 CMP.W #0x000a,&x0x8074: 340C JGE (C$DW$L$main$2$E) C$DW$L$main$2$B, C$L1:0x8076: 421F 0214 MOV.W &x,R150x807a: 5F0F RLA.W R150x807c: 429F 0214 0200 MOV.W &x,0x0200(R15)0x8082: 5392 0214 INC.W &x0x8086: 90B2 000A 0214 CMP.W #0x000a,&x0x808c: 3BF4 JL (C$L1) C$L2, C$DW$L$main$2$E:0x808e: 430C CLR.W R120x8090: 4130 RET
Arrays
Pointers and Arrays 9BYU CS 224
C Strings A C string is an array of characters:
char outputString[16]; C strings are terminated with a zero byte. C strings can be initialized when defined:
char outputString[] = "Text";which is the same as:
outputString[0] = 'T';outputString[1] = 'e';outputString[2] = 'x';outputString[3] = 't';outputString[4] = 0;
C has no string operators. String functions in <string.h> library strcpy strlen strcmp strstr, …
C Strings
Compiler computes the size
of the array(4 + 1 = 5 bytes)
Pointers and Arrays 10BYU CS 224
Common Pitfalls with Arrays Overrun array limits.
There is no boundary checking in C.
int array[10], i;for (i = 0; i <= 10; i++) // oops array[i] = 0;
Arrays must be statically declared Compiler flags run-time declarations
void SomeFunction(int num_elements){ int temp[num_elements]; // error …}
Arrays
Pointers and Arrays 11BYU CS 224
Passing Arrays as Arguments C passes parameters to functions by value. C passes the address of the 1st element of an array.
Array Arguments
0x05e8
values 0x05ea
i 0x05ec
sum 0x05ee
0x05f0 Return Adr
nums[0] 0x05f2
nums[1] 0x05f4
nums[2] 0x05f6
nums[3] 0x05f8
nums[4] 0x05fa
mean 0x05fc
0x05fe Return Adr
0x0600
4
35
3
#define MAX_NUMS 5int average(int values[]){
int i, sum = 0;for (i = 0; i < MAX_NUMS; i++)
sum = sum + values[i];return (sum / MAX_NUMS);
}
int main(){
int nums[MAX_NUMS] ={ 1, 2, 3, 4, 5 };
int mean = average(nums);return 0;
}
21
155
0x05f2SP
SP
Pointers and Arrays 12
// quiz 8.1#define NUMS 5int average(int data[]){ int i, sum = 0; for (i = 0; i < NUMS; i++) sum = sum + data[i]; return (sum / NUMS);}
int nums[NUMS] = {1, 2, 3, 4, 5};int main(){ printf("%d", average(nums)); return 0;}
BYU CS 224
Quiz 8.11. How big is the activation
record for the function average?
2. How much, where, and when is memory allocated for the variable data?
3. How much, where, and when is memory allocated for the variable sum?
4. How much, where, and when is memory allocated for nums?
Pointers
Pointers and Arrays 14BYU CS 224
Swap Function Example
int main(){ int a = 3; int b = 4; swap(a, b);}
void swap(int a, int b){ int temp = a; a = b; b = temp;}
0x05ea
0x05ec
0x05ee
0x05f0
0x05f2
0x05f4
0x05f6
0x05f8
a 0x05fa 3
b 0x05fc 4
0x05fe Return Adr
0x0600
main
3Return Adr
ab
tempswap 3
4
Pointers
Stack after call to swap():
Pointers and Arrays 15BYU CS 224
Pointers A pointer is an address
With pointers functions can indirectly access variables. functions can modify the arguments passed by the caller function. sophisticated data structures can grow and shrink at run-time.
Arrays and pointers are closely related. Array pointers enable us to conveniently process groups of data such
as vectors, lists, and strings. A pointer variable contains a memory address
Associated with a pointer variable is the type of value to which it points.
The asterisk (*) indicates that the following identifier is a pointer variable.
The ampersand (&) returns a pointer (address) to the following identifier.
Pointers
int* ptr;char* cp;double* dp;int** p_ptr = &ptr;char *strings[10];
Pointers and Arrays 16BYU CS 224
Pointer Operators A pointer variable is declared with the asterisk operator (*)
type *var; // same - whitespace doesn’t matter
type* var; Dereferencing any expression returns a value
*var returns contents of the memory locationpointed to by var
**var returns contents of the memory locationpointed to by the memory location pointedto by var
*3 returns the contents of memory location 3 A pointer is created with the reference operator (&)
&var Reference must be applied to a memory object &3 is illegal as it would return a pointer to a constant
Pointers
Pointers and Arrays 17BYU CS 224
Operator Precedence and Associativity
OPERATORS ASSOCIATIVITY( ) [ ] -> . left to right! ~ ++ -- + - * & (type) sizeof right to left* / % left to right+ - left to right<< >> left to right< <= > >= left to right== != left to right& left to right^ left to right| left to right&& left to right|| left to right?: left to right= += -= *= /= %= &= ^= |= <<= >>= right to left, left to right
Pointers
* =dereference& = reference
Pointers and Arrays 18BYU CS 224
Examples of Pointers
int *ptr1;int *ptr2;int i = 4;int j;ptr1 = &i;ptr2 = &j;
// What will these print?
printf("\n%04x", ptr1);printf("\n%04x", ptr2);printf("\n%04x", *ptr1);printf("\n%04x", *ptr2);j = *ptr1;printf("\n%04x", j);
0x05fa0x05fc0x0004??????
0x0004
0x05ea
0x05ec
0x05ee
0x05f0
0x05f2
0x05f4
ptr1 0x05f6
ptr2 0x05f8
i 0x05fa
j 0x05fc
0x05fe Return Adr
0x0600
44
0x05fc0x05fa
Pointers
Pointers and Arrays 19BYU CS 224
Swap Example Fixed! Stack after call to swap()
int main(){ int a = 3; int b = 4; swap(&a, &b);}
void swap(int* a, int* b){ int temp = *a; *a = *b; *b = temp;}
0x05ea
0x05ec
0x05ee
0x05f0
0x05f2
0x05f4
0x05f6
0x05f8
a 0x05fa 3b 0x05fc 4
0x05fe Return Adr0x0600
main
3Return Adr
ab
tempswap 0x05fc
0x05fa
Swap Example w/Pointers
43
Pointers and Arrays 20BYU CS 224
Null Pointers Sometimes we want a pointer that points to nothing.
Used for invalid pointer error returns Used to catch errors
NULL is a predefined macro that contains a value that non-null pointer should never hold, usually NULL=0.
int *p; p = NULL; // p is a null pointer
Null Pointers
Pointer Arithmetic
Pointers and Arrays 22BYU CS 224
Pointer Arithmetic Address calculations depend on size of elements
ints are 16-bits or 2 bytes per element. e.g., to find 4th element (x[3]), we add 3*2 to base address
If double, we'd have to add 12 (3*4) to find address of 4th element.
C does size calculations under the covers,depending on size of item being pointed to:
double x[10];double *y = x;*(y + 3) = 13;y++;*y = 3.1415926;
Allocates 40 bytes(4 per element)
Same as x[3](base address plus
12)
Pointer Arithmetic
x[1] = 3.1415926
Pointers and Arrays 23BYU CS 224
1
Incrementing Pointers A pointer increments according to its type. The unary operators * and & bind more tightly than
arithmetic operators.
9
0x05f2
1317
5
int y = 0;int a[5] = {1, 5, 9, 13, 17};int* ip = &a[0];
y = *ip + 1;*ip += 1;y = ++*ip;y = *ip++;y = (*ip)++;
Pointer Arithmetic
02
// y = a[0]+1 y=2, ip=0x05f2// a[0] = a[0]+1 y=2, ip=0x05f2
2
// y = ++a[0] y=3, ip=0x05f2
33
// y=a[1], a[1]++ y=5, ip=0x05f4
5
6
0x05ee
y 0x05f0
a[0] 0x05f2
a[1] 0x05f4
a[2] 0x05f6
a[3] 0x05f8
a[4] 0x05fa
ip 0x05fc
0x05fe Return Adr
0x0600// y = a[0], ip++ y=3, ip=0x05f4
0x05f4
Pointers and ArraysBYU CS 224
Quiz 8.2
// quiz 8.2void main(void){ char dog[] = {1, 2, 3, 4, 5, 6}; int cat[] = {1, 2, 3, 4, 5, 6); long pig[] = {1, 2, 3, 4, 5, 6); char* apple = dog; int* orange = cat; long* banana = pig;
printf("\n%d", *(++apple + 2)); printf("\n%d", &orange[5] - cat); printf("\n%d", (int)&orange[5] - (int)cat); printf("\n%d", (pig + 2) - banana); printf("\n%d", (int)(pig + 2) - (int)&banana[0]);}
1. What is output?
24
Pointers and Arrays 25BYU CS 224
*ip++ Form used by “experienced” C programmers
// strcpy: copy s to d; version 1void strcpy(char* d, char* s){
while ((*d = *s) != ‘\0’){
d++;s++;
}}
// strcpy: copy s to d; version 2void strcpy(char* d, char* s){
while ((*d++ = *s++) != ‘\0’);}
The value of *s++ is the character that s pointed to before s was incremented; the postfix ++ does not change s until after this character has been fetched.
Pointer Arithmetic
Pointers and Arrays 26BYU CS 224
Arrays and Pointers Array names are NOT pointer variables
char a[6]; Requests memory for 6 characters, to be known by the name “a”. “a” is not a variable and known only at compile time (ie. defined in
the compiler symbol table). char *p;
Requests memory for a single pointer variable, to be known by the name “p”.
“p” can point to any char (or contiguous array of chars). Example:
char a[] = "hello";char *p = "world";
\0olleha:
p: \0dlrow
Pointers and Arrays 27BYU CS 224
Arrays and Pointers An array name (at compile time) is essentially a pointer to
the first element in an array. Can change the value (contents) of a pointer.
char arr[10];char *cptr = arr; // points to
arr[0]char c = *(cptr+2); // arr[2]c = 4[cptr]; // arr[4]
Each of the following lines evaluate the same:
Arrays and Pointers
cptr arr &0[arr] &arr[0] address of arr[0](cptr + n) (arr + n) &n[arr] &arr[n] address of arr[n]*cptr *arr 0[arr] arr[0] value of arr[0] *(cptr + n) *(arr + n) n[arr] arr[n] value of arr[n]
Pointers and Arrays 28BYU CS 224
Quiz 8.3 Show 3 different ways to access the character 'o' in the array x
without using brackets.
char x[] = "Hello";char* y = x;char** z = &y;
Pointers and More…
BYU CS 224 Pointers and Arrays 30
const Pointers In C, const is a type qualifier keyword applied to a data
type that indicates to the compiler that the data is constant (does not vary).
const modifies the name to its right.
int* ptr1;
int const *ptr2;
int* const ptr3;
int const * const ptr4;
const
ptr1 is a (mutable)pointer to an int
ptr2 is a pointerto a (non-mutable) int
ptr3 is a (non-mutable)pointer to an int
ptr4 is a(non-mutable) pointerto a (non-mutable) int
Pointers and Arrays 31
The function scanf is similar to printf, providing many of the same conversion facilities in the opposite direction:
scanf( const char *format, ... );scanf("%s = %f", name, &cost);
BYU CS 224
Formatted Input/Output The printf function outputs formatted values to the
stdout stream using putcprintf( const char *format, ... );printf("\nX = %d, Y = %d", x, y);
C I/O
Output y as an ASCII string
Decimal "%d" or "%i"
String "%s" Character "%c“ Hexadecimal "%x“ Unsigned decimal "%u
Floating point "%f" Scientific notation
"%e" Pointer
"%p" % "%
%"
name and costMUST be pointers
Function Pointers
Lab 9b - Snake Lab 33BYU CS 224
Function Pointers In C, a function name is an address. As such, it is possible to define
pointers to functions which can be: assigned, changed, placed in arrays, passed and returned from functions, used as “callbacks” to other functions, and so on.
The format of a function pointer looks like:
To write and use a function pointer:
<type> (*POINTER_NAME)(<parameters...>)
1. Normal function declaration: int callme(int a, int b);2. Wrap function name: int (*callme)(int a, int
b);3. Change the name: int (*myFunc)(int a, int
b);4. Use as function: dog = (*myFunc)(10, 20);
Lab 9b - Snake Lab 34BYU CS 224
Function Pointers
int add(int x, int y) { return x + y; }int subtract(int x, int y) { return x - y; }
int domath(int (*mathop)(int, int), int x, int y) { return (*mathop)(x, y);}
int main(){ printf("Add: %d\n", domath(add, 10, 2)); printf("Subtract: %d\n", domath(subtract, 10, 2));}
Function pointers can be passed as function parameters and used as “call-backs”.
A function name (label) is converted to a pointer to itself and can be used where function pointers are required as input.
Example:
Pointers and Arrays 35BYU CS 224
Static Variables Static functions are local to a file. Static variables are “global local” variables.
May be declared inside a C function. Like local variables, a static variable cannot be referred from
outside the function. However, unlike a local variable, the value continues to exist
even after the function exits. The value comes back into scope when the function is called
again (value retained). A function can pass out a pointer to a static variable and de-
reference the value.
static int sum = 0;
Static Variables
Pointers and Arrays 36BYU CS 224
Static Function Variables What does this function do? Does it compile? Work as intended? How would you fix it?
Static Variables
int next_Factorial(void){
int current = 1;int next = 1;current *= next++;return current;
} // next_Factorial
printf("%d ", next_Factorial());printf("%d ", next_Factorial());...
int next_Factorial(void){
static int current = 1;static int next = 1;current *= next++;return current;
} // next_Factorial
printf("%d ", next_Factorial());printf("%d ", next_Factorial());...
Pointers and Arrays 37BYU CS 224
Pointers to Pointers Since pointers are variables themselves, they can be
stored in arrays just as other variables can.Example:
char* lines[8];char** linesptr = lines;
linesptr[0]linesptr[1]linesptr[2]
…
defghi
abc
lmnopqrstuvwxyz
Pointers to Pointers
char* lines[8];//char** linesptr = &lines[0];//char** linesptr = &*lines;char** linesptr = lines;
linesptr[0][0] = 'c';
Pointers and Arrays 38BYU CS 224
linesptr[0]linesptr[1]linesptr[2]
…
Pointers to Pointers Since pointers are variables themselves, they can be
stored in arrays just as other variables can.Example:
char* lines[8];char** linesptr = lines;
defghi
abc
lmnopqrstuvwxyz
Pointers to Pointers
Pointers and Arrays 39BYU CS 224
Multi-dimensional Arrays Multi-dimensional arrays declared with multiple indexes
Pointers to pointers… day[i][j] /* [row][col] */ day[i,j] /* Syntax Error! */
Array elements are stored by rows The rightmost subscript varies the fastest Array name “points” to 1st element
Multi-dimensional arrays passed to a function by value (address of 1st element in 1st row, 1st column… must declare the number of elements for every subscript except
the first func(int day[ ][13]) {…}
Multi-dimensional Arrays
The main Function The main function
must be present in every C program. is “called” by the operating system. exits the program with a return statement.
The prototype of main is pre-declared as:
int main (int argc, char *argv[]);
The definition doesn’t have to match.
int main() { ... }main() { ... }
The return statement can be omitted.
BYU CS 224 Pointers and Arrays 40
These are OK
main Function
Return code for system # of command
line arguments
C main to Assembly
BYU CS 224 Pointers and Arrays 41
int main(int argc, char** argv){
unsigned int x = 7;unsigned int y = 5;unsigned int z;
z = x * y;return 0;
}
main:0x8040: 8031 000A SUB.W #0x000a,SP0x8044: 4D81 0002 MOV.W R13,0x0002(SP)0x8048: 4C81 0000 MOV.W R12,0x0000(SP)0x804c: 40B1 0007 0004 MOV.W #0x0007,0x0004(SP)0x8052: 40B1 0005 0006 MOV.W #0x0005,0x0006(SP)0x8058: 411C 0004 MOV.W 0x0004(SP),R120x805c: 411D 0006 MOV.W 0x0006(SP),R130x8060: 12B0 80DA CALL #__mpyi0x8064: 4C81 0008 MOV.W R12,0x0008(SP)0x8068: 430C CLR.W R120x806a: 5031 000A ADD.W #0x000a,SP0x806e: 4130 RET
__mpyi:0x80da: 430E CLR.W R14 mpyi_add_loop:0x80dc: C312 CLRC0x80de: 100C RRC R120x80e0: 2801 JLO shift_test_mpyi0x80e2: 5D0E ADD.W R13,R14 shift_test_mpyi:0x80e4: 5D0D RLA.W R130x80e6: 930C TST.W R120x80e8: 23F9 JNE mpyi_add_loop0x80ea: 4E0C MOV.W R14,R120x80ec: 4130 RET
SP
Stack
x05f4x05f6x05f8x05fa
x0600
x05fcx05fe
ret adr
argc (r12)argv (r13)
xyz
main Function
Pointers and Arrays 42
Quiz 8.4
List the output of the following echo C program as called by:
>>echo Good Morning America
int main(int argc, char* argv[ ]){
while (--argc > 0) {
printf("%s%s", *++argv, (argc > 1) ? " " : ""); }
printf("\n");return 0;
}BYU CS 224
Pointers and Arrays 43BYU CS 224