Presentation is loading. Please wait.

Presentation is loading. Please wait.

Chapter 15 - Arrays and Pointers. BYU CS/ECEn 124Arrays and Pointers2 Lab 8 – Etch-a-Sketch An analog-to-digital converter converts continuous analog.

Similar presentations


Presentation on theme: "Chapter 15 - Arrays and Pointers. BYU CS/ECEn 124Arrays and Pointers2 Lab 8 – Etch-a-Sketch An analog-to-digital converter converts continuous analog."— Presentation transcript:

1 Chapter 15 - Arrays and Pointers

2 BYU CS/ECEn 124Arrays and Pointers2 Lab 8 – Etch-a-Sketch An analog-to-digital converter converts continuous analog signals to discrete digital numbers. Jitter is the physical phenomenon that results from "noise" associated with a analog signal. manifests itself by the return values "dancing around“ Eliminate noise and smooth out input data using A lowpass filter... Oversampling... Thresholds...

3 BYU CS/ECEn 124Arrays and Pointers3 Lab 8 – Etch-a-Sketch Digital equivalent of an analog low pass RC filter unsigned int lowpass_filter(unsigned int input, unsigned int* delay) { // Update filter with current sample. *delay = *delay - (*delay >> FILTER_SHIFT) + input; // Scale output for unity gain. return *delay >> FILTER_SHIFT; }

4 BYU CS/ECEn 124Arrays and Pointers4 Lab 8 – Etch-a-Sketch Digital equivalent of an analog low pass RC filter 1514131211109876543210 Output delay_element += Input – (delay_element >> 4))

5 BYU CS/ECEn 124Arrays and Pointers5 Lab 8 – Etch-a-Sketch #define FILTER_SHIFT 3// Parameter K // initial lowpass filter delay values oldx = ADC_read(LEFT_POT); oldy = ADC_read(RIGHT_POT); pot1_delay = (oldx > FILTER_SHIFT);; pot2_delay = (oldy > FILTER_SHIFT);; while(1) { // pass through low-pass filter x = lowpass_filter(ADC_read(LEFT_POT), &pot1_delay); y = lowpass_filter(ADC_read(RIGHT_POT), &pot2_delay); } unsigned int lowpass_filter(unsigned int input, unsigned int* delay) { // Update filter with current sample. *delay += input - (*delay >> FILTER_SHIFT); // Scale output for unity gain. return (*delay >> FILTER_SHIFT); }

6 BYU CS/ECEn 124Arrays and Pointers6 Concepts to Learn… Arrays C Strings Array Arguments Pointers Pointer Arithmetic Swap Example w/Pointers Null Pointers Arrays and Pointers Pointers to Pointers Multi-dimensional Arrays Command-line Arguments Function Pointers

7 BYU CS/ECEn 124Arrays and Pointers7 Arrays Allocate a sequence of memory locations. For example - table of numbers Problems What if there are 1000 numbers? Write a loop to process each number? Use an array Declare a sequence of four integers. int num[4]; num[0], num[1], num[2], num[3]. An array is a sequence of like items. int num0; int num1; int num2; int num3; Arrays

8 BYU CS/ECEn 124Arrays and Pointers8 Array Syntax Like any other variable, 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. General form: variable-name[index]; Zero based subscripts No compile-time or run-time limit checking Arrays

9 BYU CS/ECEn 124Arrays and Pointers9 Initialization of Arrays Elements can be initialized in the same way as the ordinary variables when they are declared. type array_name[size]={ list of values }; int number[3] = {0, 0, 0}; Remaining uninitialized elements will be set to zero automatically. Array declarations may omit the size. int counter[] = {1, 1, 1, 1}; Problems with C initialization of arrays No convenient way to initialize selected elements. No shortcut to initialize large number of elements. Arrays

10 BYU CS/ECEn 124Arrays and Pointers10 Local Array Example int main() { int array[10]; int x; x = array[3] + 1; array[6] = 5; return 0; } main: 0x87a2: 8031 0016 SUB.W #0x0016,SP 0x87a6: 431F MOV.W #1,R15 0x87a8: 511F 0006 ADD.W 0x0006(SP),R15 0x87ac: 4F81 0014 MOV.W R15,0x0014(SP) 0x87b0: 40B1 0005 000C MOV.W #0x0005,0x000c(SP) 0x87b6: 430C CLR.W R12 0x87b8: 5031 0016 ADD.W #0x0016,SP 0x87bc: 4130 RET Arrays array[0]0x0000(SP) array[1]0x0002(SP) array[2]0x0004(SP) array[3]0x0006(SP) array[4]0x0008(SP) array[5]0x000a(SP) array[6]0x000c(SP) array[7]0x000e(SP) array[8]0x0010(SP) array[9]0x0012(SP) x0x0014(SP) SP 

11 BYU CS/ECEn 124Arrays and Pointers11 Local Array Example int main() { int array[10]; int x; for (x = 0; x < 10; x++) { array[x] = x; } return 0; } main: 0x8040: 8031 0016 SUB.W #0x0016,SP 0x8044: 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),R15 0x8054: 5F0F RLA.W R15 0x8056: 510F ADD.W SP,R15 0x8058: 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 R12 0x806c: 5031 0016 ADD.W #0x0016,SP 0x8070: 4130 RET Arrays array[0]0x0000(SP) array[1]0x0002(SP) array[2]0x0004(SP) array[3]0x0006(SP) array[4]0x0008(SP) array[5]0x000a(SP) array[6]0x000c(SP) array[7]0x000e(SP) array[8]0x0010(SP) array[9]0x0012(SP) x0x0014(SP) SP 

12 BYU CS/ECEn 124Arrays and Pointers12 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 &x 0x806e: 90B2 000A 0214 CMP.W #0x000a,&x 0x8074: 340C JGE (C$DW$L$main$2$E) C$DW$L$main$2$B, C$L1: 0x8076: 421F 0214 MOV.W &x,R15 0x807a: 5F0F RLA.W R15 0x807c: 429F 0214 0200 MOV.W &x,0x0200(R15) 0x8082: 5392 0214 INC.W &x 0x8086: 90B2 000A 0214 CMP.W #0x000a,&x 0x808c: 3BF4 JL (C$L1) C$L2, C$DW$L$main$2$E: 0x808e: 430C CLR.W R12 0x8090: 4130 RET Arrays

13 BYU CS/ECEn 124Arrays and Pointers13 Array Example int array[10]; int x; grid[x+1] = grid[x] + 2; 0x86aa: 411F 0014 MOV.W 0x0014(SP),R15 0x86ae: 5F0F RLA.W R15 0x86b0: 510F ADD.W SP,R15 0x86b2: 432E MOV.W #2,R14 0x86b4: 5F2E ADD.W @R15,R14 0x86b6: 411F 0014 MOV.W 0x0014(SP),R15 0x86ba: 5F0F RLA.W R15 0x86bc: 532F INCD.W R15 0x86be: 510F ADD.W SP,R15 0x86c0: 4E8F 0000 MOV.W R14,0x0000(R15) Arrays array[0]0x0000(SP) array[1]0x0002(SP) array[2]0x0004(SP) array[3]0x0006(SP) array[4]0x0008(SP) array[5]0x000a(SP) array[6]0x000c(SP) array[7]0x000e(SP) array[8]0x0010(SP) array[9]0x0012(SP) x0x0014(SP) SP 

14 BYU CS/ECEn 124Arrays and Pointers14 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 library C Strings Compiler computes the size of the array (4 + 1 = 5 bytes)

15 BYU CS/ECEn 124Arrays and Pointers15 Strings are Arrays int main() { char string[] = "\nhello!"; printf("%s", string); } C Strings 0x05e8 0x05ea 0x05ec 0x05ee 0x05f0 0x05f2 0x05f4 string[0]0x05f6 string[2]0x05f8 string[4]0x05fa string[6]0x05fc 0x05feReturn Adr 0x0600 0x6c/0x65 0x00/0x21 0x6f/0x6c 0x61/0x0a  SP

16 BYU CS/ECEn 124Arrays and Pointers16 Passing Arrays as Arguments C passes parameters to functions by value. C passes the address of the 1 st element by value. Array Arguments 0x05e8 values0x05ea i0x05ec sum0x05ee 0x05f0Return Adr n[0]0x05f2 n[1]0x05f4 n[2]0x05f6 n[3]0x05f8 n[4]0x05fa mean0x05fc 0x05feReturn Adr 0x0600 4 3 5 3 #define MAX_NUMS 5 int 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; } 2 1 15 5 0x05f2 SP 

17 Pointers

18 BYU CS/ECEn 124Arrays and Pointers18 Pointers A pointer is a variable that contains 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. Pointers

19 BYU CS/ECEn 124Arrays and Pointers19 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 a0x05fa 3 b0x05fc 4 0x05fe Return Adr 0x0600 main 3 Return Adr a b temp swap 3 4 Pointers Stack after call to swap():

20 BYU CS/ECEn 124Arrays and Pointers20 Pointer Variables Pointer variables contain memory addresses. 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. Pointer examples: int* ptr; char* cp; double* dp; int** p_ptr = &ptr; char *strings[10]; Pointers

21 BYU CS/ECEn 124Arrays and Pointers21 Syntax for 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 *varreturns contents of the memory location pointed to by var **varreturns contents of the memory location pointed to by the memory location pointed to by var *3returns 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

22 BYU CS/ECEn 124Arrays and Pointers22 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); 0x05fa 0x05fc 0x0004 ?????? 0x0004 0x05ea 0x05ec 0x05ee 0x05f0 0x05f2 0x05f4 ptr10x05f6 ptr20x05f8 i0x05fa j0x05fc 0x05fe Return Adr 0x0600 4 4 0x05fc 0x05fa Pointers

23 BYU CS/ECEn 124Arrays and Pointers23 Operator Precedence and Associativity OPERATORSASSOCIATIVITY ( ) [ ] ->.left to right ! ~ ++ -- + - * & (type) sizeofright 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 = += -= *= /= %= &= ^= |= >=right to left,left to right Pointers * =dereference & = reference

24 BYU CS/ECEn 124Arrays and Pointers24 Pointer Arithmetic Address calculations depend on size of elements ints are 16-bits or 2 bytes per element. e.g., to find 4th element, we add 4*2 to base address If double, we'd have to add 16 (4*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; Allocates 40 bytes (4 per element) Same as x[3] (base address plus 12) Pointer Arithmetic

25 BYU CS/ECEn 124Arrays and Pointers25 Incrementing Pointers A pointer increments according to its type. The unary operators * and & bind more tightly than arithmetic operators. //y=0, ip=0x05f2 // y = a[0]+1y=2, ip=0x05f2 // a[0] = a[0]+1y=2, ip=0x05f2 // a[0] = a[0]+1y=3, ip=0x05f2 // ip = ip+1y=3, ip=0x05f4 // a[1] = a[1]+1y=5, ip=0x05f4 0x05ee y0x05f0 a[0]0x05f2 a[1]0x05f4 a[2]0x05f6 a[3]0x05f8 a[4]0x05fa ip0x05fc 0x05fe Return Adr 0x0600 9 0x05f2 13 17 5 1 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

26 BYU CS/ECEn 124Arrays and Pointers26 *ip++  Form used by “experienced” C programmers // strcpy: copy s to d; version 1 void strcpy(char* d, char* s) { while ((*d = *s) != ‘\0’) { d++; s++; } // strcpy: copy s to d; version 2 void 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

27 BYU CS/ECEn 124Arrays and Pointers27 Incrementing Pointers int main() { char *cptr; double *fptr; char buffer[10]; double array[10]; cptr = buffer;// cptr = &buffer[0]; fptr = array;// fptr = &array[0]; printf("\n0x%04d, 0x%04d", cptr++, fptr++); printf("\n0x%04d, 0x%04d", cptr, fptr); return 0; } 0x05cc, 0x05d6 0x05cd, 0x05da Pointer Arithmetic

28 BYU CS/ECEn 124Arrays and Pointers28 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 a0x05fa 3 b0x05fc 4 0x05fe Return Adr 0x0600 main 3 Return Adr a b temp swap 0x05fc 0x05fa Swap Example w/Pointers 4 3

29 BYU CS/ECEn 124Arrays and Pointers29 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

30 Pointers and Arrays

31 BYU CS/ECEn 124Arrays and Pointers31 Arrays and Pointers An array name is essentially a pointer to the first element in an array. Can change the value (contents) of a pointer. char word[10]; char *cptr; cptr = word; // points to word[0] Arrays and Pointers

32 BYU CS/ECEn 124Arrays and Pointers32 Arrays and Pointers Given the previous declarations, each of the following lines are equal. cptrword&word[0] address of word[0] (cptr + n)word + n&word[n] address of word[n] *cptr*wordword[0] value of word[0] *(cptr + n)*(word + n)word[n] value of word[n] char word[10]; char *cptr; cptr = word; // points to word[0] Arrays and Pointers

33 BYU CS/ECEn 124Arrays and Pointers33 Address calculations depend on size of elements char x[4] – add 4 to base address int x[4] – add 8 (2*4) to base address long x[4] – add 16 (4*4) to base address C does size calculations behind the scenes, depending on type of pointer (size of item being pointed to) long x[10];// allocates 40 bytes long *y = x; *(y + 3) = 13;// same as x[3] = 13 Array Pointer Arithmetic Arrays and Pointers

34 BYU CS/ECEn 124Arrays and Pointers34 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 and Pointers

35 BYU CS/ECEn 124Arrays and Pointers35 Initialization of Pointer Arrays Pointer arrays can be initialized as follows: /* month_name: return name of n-th month */ char* month_name(int n) { static char* name[ ] = {"Illegal month", "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" }; return ( n 12 ) ? name[0] : name[n]; } Arrays and Pointers

36 Pointers and More…

37 BYU CS/ECEn 124Arrays and Pointers37 Pointers to Pointers Since pointers are variables themselves, they can be stored in arrays just as other variables can. Example: char* linesptr[8]; linesptr[0] linesptr[1] linesptr[2] … defghi  abc  lmnopqrstuvwxyz  Pointers to Pointers

38 BYU CS/ECEn 124Arrays and Pointers38 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* linesptr[8]; defghi  abc  lmnopqrstuvwxyz  Pointers to Pointers

39 BYU CS/ECEn 124Arrays and Pointers39 Multi-dimensional Arrays Multi-dimensional arrays declared with multiple indexes daytab[i][j]/* [row][col] */ daytab[i,j]/* WRONG! */ Array elements are stored by rows The rightmost subscript varies the fastest Array name “points” to 1 st element Multi-dimensional arrays passed to a function must declare the number of elements for every subscript except the first func(int daytab[ ][13]) {…} Multi-dimensional Arrays

40 BYU CS/ECEn 124Arrays and Pointers40 Command-line Arguments When main is called, it is passed two arguments. The first (conventionally called argc, for argument count) is the number of command-line arguments the program was invoked with. The second ( argv, for argument vector) is a pointer to an array of character pointers (strings) that contain the arguments, one per string. By conventions, argv[0] points to the name by which the program was invoked. By standards, argv[argc] is a null pointer. Command-line Arguments

41 BYU CS/ECEn 124Arrays and Pointers41 Command-line Arguments By standards, argv[argc] is a null pointer. echo\0 hello\0 world\0 argv: /* echo command-line arguments int main(int argc, char* argv[ ]) { while (--argc > 0) printf("%s%s", *++argv, (argc > 1) ? " " : ""); printf("\n"); return 0; } Command-line Arguments

42 BYU CS/ECEn 124Arrays and Pointers42 Function Pointers In C, a function is not a variable, but it is possible to define pointers to functions which can be: assigned, placed in arrays, passed to functions, returned by functions, and so on. int function1(int a, char* s) { … } int function2(int a, char* s) { … } int (*f[2])(int, char*); f[0] = function1; f[1] = function2; (*f[n])(10, "hello"); Function Pointers

43 BYU CS/ECEn 124Arrays and Pointers43 Complicated Declarations C is sometimes castigated for the syntax of declarations, particularly ones that involve pointers to functions: int *f(); // f: function returning pointer to int int (*pf)(); // pf: pointer to function returning int What do these do? char **argv argv: pointer to pointer to char int (*daytab)[13] daytab: pointer to array[13] of int int *daytab[13] daytab: array[13] of pointer to int char (*(*x())[])() x: function returning pointer to array[ ] of pointers to function returning char char (*(*x[3])())[5] x: array[3] of pointer to function returning pointer to array[5] of char Function Pointers

44 BYU CS/ECEn 124Arrays and Pointers44


Download ppt "Chapter 15 - Arrays and Pointers. BYU CS/ECEn 124Arrays and Pointers2 Lab 8 – Etch-a-Sketch An analog-to-digital converter converts continuous analog."

Similar presentations


Ads by Google