Chapter 15 - Arrays and Pointers

Download Report

Transcript Chapter 15 - Arrays and Pointers

Chapter 15 Arrays and Pointers
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...
BYU CS/ECEn 124
Arrays and Pointers
2
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;
}
BYU CS/ECEn 124
Arrays and Pointers
3
Lab 8 – Etch-a-Sketch

Digital equivalent of an analog low pass RC filter
delay_element += Input – (delay_element >> 4))
15
14
13
12
11
10
9
8
7
6
5
4
3
2
1
0
Output
BYU CS/ECEn 124
Arrays and Pointers
4
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) + (oldx >> FILTER_SHIFT);;
pot2_delay = (oldy << FILTER_SHIFT) + (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);
}
BYU CS/ECEn 124
Arrays and Pointers
5
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
BYU CS/ECEn 124
Arrays and Pointers
6
Arrays
Arrays

Allocate a sequence of memory locations.


For example - table of numbers
Problems



num0;
num1;
num2;
num3;
Use an array

Declare a sequence of four integers.



What if there are 1000 numbers?
Write a loop to process each number?
int
int
int
int
int num[4];
num[0], num[1], num[2], num[3].
An array is a sequence of like items.
BYU CS/ECEn 124
Arrays and Pointers
7
Arrays
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

BYU CS/ECEn 124
Arrays and Pointers
8
Arrays
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.
BYU CS/ECEn 124
Arrays and Pointers
9
Arrays
Local Array Example
SP 
int main()
{
int array[10];
int x;
x = array[3] + 1;
array[6] = 5;
return 0;
array[0]
array[1]
array[2]
array[3]
array[4]
array[5]
array[6]
array[7]
array[8]
array[9]
x
0x0000(SP)
0x0002(SP)
0x0004(SP)
0x0006(SP)
0x0008(SP)
0x000a(SP)
0x000c(SP)
0x000e(SP)
0x0010(SP)
0x0012(SP)
0x0014(SP)
}
main:
0x87a2:
0x87a6:
0x87a8:
0x87ac:
0x87b0:
0x87b6:
0x87b8:
0x87bc:
BYU CS/ECEn 124
8031
431F
511F
4F81
40B1
430C
5031
4130
0016
0006
0014
0005 000C
0016
SUB.W
MOV.W
ADD.W
MOV.W
MOV.W
CLR.W
ADD.W
RET
#0x0016,SP
#1,R15
0x0006(SP),R15
R15,0x0014(SP)
#0x0005,0x000c(SP)
R12
#0x0016,SP
Arrays and Pointers
10
Arrays
Local Array Example
SP 
int main()
{
int array[10];
int x;
for (x = 0; x < 10; x++)
{
array[x] = x;
main:
}
0x8040: 8031
return 0;
0x8044: 4381
0x8048: 90B1
}
0x804e: 340D
0x8050:
0x8054:
0x8056:
0x8058:
0x805e:
0x8062:
0x8068:
0x806a:
0x806c:
0x8070:
BYU CS/ECEn 124
0016
0014
000A 0014
SUB.W
CLR.W
CMP.W
JGE
C$DW$L$main$2$B, C$L1:
411F 0014
MOV.W
5F0F
RLA.W
510F
ADD.W
419F 0014 0000
MOV.W
5391 0014
INC.W
90B1 000A 0014
CMP.W
3BF3
JL
C$L2, C$DW$L$main$2$E:
430C
CLR.W
5031 0016
ADD.W
4130
RET
Arrays and Pointers
array[0]
array[1]
array[2]
array[3]
array[4]
array[5]
array[6]
array[7]
array[8]
array[9]
x
0x0000(SP)
0x0002(SP)
0x0004(SP)
0x0006(SP)
0x0008(SP)
0x000a(SP)
0x000c(SP)
0x000e(SP)
0x0010(SP)
0x0012(SP)
0x0014(SP)
#0x0016,SP
0x0014(SP)
#0x000a,0x0014(SP)
(C$DW$L$main$2$E)
0x0014(SP),R15
R15
SP,R15
0x0014(SP),0x0000(R15)
0x0014(SP)
#0x000a,0x0014(SP)
(C$L1)
R12
#0x0016,SP
11
Arrays
Global Array Example
int array[10];
int x;
int main()
{
for (x = 0; x < 10; x++)
{
array[x] = x;
main:
}
0x806a: 4382
return 0;
0x806e: 90B2
0x8074: 340C
}
0x8076:
0x807a:
0x807c:
0x8082:
0x8086:
0x808c:
0x808e:
0x8090:
BYU CS/ECEn 124
0214
000A 0214
CLR.W
CMP.W
JGE
C$DW$L$main$2$B, C$L1:
421F 0214
MOV.W
5F0F
RLA.W
429F 0214 0200
MOV.W
5392 0214
INC.W
90B2 000A 0214
CMP.W
3BF4
JL
C$L2, C$DW$L$main$2$E:
430C
CLR.W
4130
RET
Arrays and Pointers
&x
#0x000a,&x
(C$DW$L$main$2$E)
&x,R15
R15
&x,0x0200(R15)
&x
#0x000a,&x
(C$L1)
R12
12
Arrays
Array Example
SP 
int array[10];
int x;
grid[x+1] = grid[x] + 2;
0x86aa:
0x86ae:
0x86b0:
0x86b2:
0x86b4:
0x86b6:
0x86ba:
0x86bc:
0x86be:
0x86c0:
411F 0014
5F0F
510F
432E
5F2E
411F 0014
5F0F
532F
510F
4E8F 0000
BYU CS/ECEn 124
MOV.W
RLA.W
ADD.W
MOV.W
ADD.W
MOV.W
RLA.W
INCD.W
ADD.W
MOV.W
array[0]
array[1]
array[2]
array[3]
array[4]
array[5]
array[6]
array[7]
array[8]
array[9]
x
0x0000(SP)
0x0002(SP)
0x0004(SP)
0x0006(SP)
0x0008(SP)
0x000a(SP)
0x000c(SP)
0x000e(SP)
0x0010(SP)
0x0012(SP)
0x0014(SP)
0x0014(SP),R15
R15
SP,R15
#2,R14
@R15,R14
0x0014(SP),R15
R15
R15
SP,R15
R14,0x0000(R15)
Arrays and Pointers
13
C Strings
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]
outputString[1]
outputString[2]
outputString[3]
outputString[4]

=
=
=
=
=
'T';
'e';
'x';
't';
0;
Compiler computes
the size of the array
(4 + 1 = 5 bytes)
C has no string operators.

String functions in <string.h> library
BYU CS/ECEn 124
Arrays and Pointers
14
C Strings
Strings are Arrays
int main()
{
char string[] = "\nhello!";
printf("%s", string);
}
string[0]
string[2]
string[4]
string[6]
BYU CS/ECEn 124
Arrays and Pointers
0x05e8
0x05ea
0x05ec
0x05ee
0x05f0
0x05f2
0x05f4
0x05f6
0x05f8
0x05fa
0x05fc
0x05fe
0x0600
0x61/0x0a
0x6c/0x65
0x6f/0x6c
Return Adr
0x00/0x21
 SP
15
Array Arguments
Passing Arrays as Arguments
C passes parameters to functions by value.
st
 C passes the address of the 1 element by value.

#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);
}
SP 
values
i
sum
SP 
int main()
{
int nums[MAX_NUMS] =
{ 1, 2, 3, 4, 5 };
int mean = average(nums);
return 0;
}
BYU CS/ECEn 124
Arrays and Pointers
n[0]
n[1]
n[2]
n[3]
n[4]
mean
0x05e8
0x05ea
0x05ec
0x05ee
0x05f0
0x05f2
0x05f4
0x05f6
0x05f8
0x05fa
0x05fc
0x05fe
0x0600
0x05f2
5
15
Return Adr
1
2
3
4
5
3
Return Adr
16
Pointers
Pointers
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.
BYU CS/ECEn 124
Arrays and Pointers
18
Pointers
Swap Function Example
int main()
{
int a = 3;
int b = 4;
swap(a, b);
}
Stack after call to swap():
void swap(int a, int b)
{
int temp = a;
a = b;
b = temp;
}
BYU CS/ECEn 124
a
b
swap
temp
main
Arrays and Pointers
a
b
0x05ea
0x05ec
0x05ee
0x05f0
0x05f2
0x05f4
0x05f6
0x05f8
0x05fa
0x05fc
0x05fe
0x0600
4
3
3
Return Adr
3
4
Return Adr
19
Pointers
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];
BYU CS/ECEn 124
Arrays and Pointers
20
Pointers
Syntax for Pointer Operators

A pointer variable is declared with the asterisk operator (*)
type *var;
type* var;

// same - whitespace doesn’t matter
Dereferencing any expression returns a value
*var
returns contents of the memory location
pointed to by var
**var returns contents of the memory location
pointed to by the memory location pointed
to 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
BYU CS/ECEn 124
Arrays and Pointers
21
Pointers
Pointers
int *ptr1;
int *ptr2;
int i = 4;
int j;
ptr1 = &i;
ptr2 = &j;
ptr1
ptr2
i
j
// What will these print?
printf("\n%04x",
printf("\n%04x",
printf("\n%04x",
printf("\n%04x",
j = *ptr1;
printf("\n%04x",
BYU CS/ECEn 124
ptr1);
ptr2);
*ptr1);
*ptr2);
0x05fa
j);
0x0004
0x05ea
0x05ec
0x05ee
0x05f0
0x05f2
0x05f4
0x05f6
0x05f8
0x05fa
0x05fc
0x05fe
0x0600
0x05fa
0x05fc
4
4
Return Adr
0x05fc
0x0004
??????
Arrays and Pointers
22
Pointers
Operator Precedence and Associativity
* =dereference
& = reference
OPERATORS
( )
[ ]
->
.
!
~
++
-+
*
& (type) sizeof
*
/
%
+
<<
>>
<
<=
>
>=
==
!=
&
^
|
&&
||
?:
= += -= *= /= %= &= ^= |= <<= >>=
,
BYU CS/ECEn 124
Arrays and Pointers
ASSOCIATIVITY
left to right
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
23
Pointer Arithmetic
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;
BYU CS/ECEn 124
Allocates 40 bytes
(4 per element)
Same as x[3]
(base address plus 12)
Arrays and Pointers
24
Pointer Arithmetic
Incrementing Pointers


A pointer increments according to its type.
The unary operators * and & bind more tightly
than arithmetic operators.
int y = 0;
int a[5] = {1, 5, 9, 13, 17};
int* ip = &a[0];
//
y=0, ip=0x05f2
y = *ip + 1; // y = a[0]+1
y=2, ip=0x05f2
*ip += 1;
// a[0] = a[0]+1 y=2, ip=0x05f2
y = ++*ip;
// a[0] = a[0]+1 y=3, ip=0x05f2
y = *ip++;
// ip = ip+1
y=3, ip=0x05f4
y = (*ip)++; // a[1] = a[1]+1 y=5, ip=0x05f4
BYU CS/ECEn 124
Arrays and Pointers
y
a[0]
a[1]
a[2]
a[3]
a[4]
ip
0x05ee
0x05f0
0x05f2
0x05f4
0x05f6
0x05f8
0x05fa
0x05fc
0x05fe
0x0600
1
5
9
13
17
0x05f2
Return Adr
25
Pointer Arithmetic
*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.
BYU CS/ECEn 124
Arrays and Pointers
26
Pointer Arithmetic
Incrementing Pointers
int main()
{
char *cptr;
double *fptr;
char buffer[10];
double array[10];
cptr = buffer;
fptr = array;
// cptr = &buffer[0];
// fptr = &array[0];
printf("\n0x%04d, 0x%04d", cptr++, fptr++);
printf("\n0x%04d, 0x%04d", cptr, fptr);
return 0;
}
0x05cc, 0x05d6
0x05cd, 0x05da
BYU CS/ECEn 124
Arrays and Pointers
27
Swap Example w/Pointers
Swap Example Fixed!

Stack after call to swap()
int main()
{
int a = 3;
int b = 4;
swap(&a, &b);
}
a
b
swap
temp
void swap(int* a, int* b)
{
int temp = *a;
*a = *b;
*b = temp;
}
BYU CS/ECEn 124
main
Arrays and Pointers
a
b
0x05ea
0x05ec
0x05ee
0x05f0
0x05f2
0x05f4
0x05f6
0x05f8
0x05fa
0x05fc
0x05fe
0x0600
0x05fa
0x05fc
3
Return Adr
3 4
4 3
Return Adr
28
Null Pointers
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 */
BYU CS/ECEn 124
Arrays and Pointers
29
Pointers and Arrays
Arrays and Pointers
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]
BYU CS/ECEn 124
Arrays and Pointers
31
Arrays and Pointers
Arrays and Pointers
char word[10];
char *cptr;
cptr = word; // points to word[0]

Given the previous declarations, each of the
following lines are equal.
cptr
word
&word[0]
address of word[0]
(cptr + n)
word + n
&word[n]
address of word[n]
*cptr
*word
word[0]
value of word[0]
*(cptr + n)
*(word + n)
word[n]
value of word[n]
BYU CS/ECEn 124
Arrays and Pointers
32
Arrays and Pointers
Array Pointer Arithmetic

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
BYU CS/ECEn 124
Arrays and Pointers
33
Arrays and Pointers
Common Pitfalls with Arrays

Overrun array limits.

There is no boundary checking in C.
int array[10], i;
for (i = 0; i <= 10; i++)
array[i] = 0;

// oops
Arrays must be statically declared

Compiler flags run-time declarations
void SomeFunction(int num_elements)
{
int temp[num_elements];
// error
…
}
BYU CS/ECEn 124
Arrays and Pointers
34
Arrays and Pointers
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 < 1 || n > 12 ) ? name[0] : name[n];
}
BYU CS/ECEn 124
Arrays and Pointers
35
Pointers and More…
Pointers to Pointers
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]
…
BYU CS/ECEn 124
defghi
lmnopqrstuvwxyz
abc
Arrays and Pointers
37
Pointers to Pointers
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]
…
BYU CS/ECEn 124
defghi
lmnopqrstuvwxyz
abc
Arrays and Pointers
38
Multi-dimensional Arrays
Multi-dimensional Arrays

Multi-dimensional arrays declared with multiple
indexes



/* [row][col] */
/* WRONG! */
Array elements are stored by rows



daytab[i][j]
daytab[i,j]
The rightmost subscript varies the fastest
Array name “points” to 1st element
Multi-dimensional arrays passed to a function
must declare the number of elements for every
subscript except the first

func(int daytab[ ][13]) {…}
BYU CS/ECEn 124
Arrays and Pointers
39
Command-line Arguments
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.
BYU CS/ECEn 124
Arrays and Pointers
40
Command-line Arguments
Command-line Arguments

By standards, argv[argc] is a null pointer.
argv:
echo\0
hello\0
world\0
/* echo command-line arguments
int main(int argc, char* argv[ ])
{
while (--argc > 0)
printf("%s%s", *++argv, (argc > 1) ? " " :
"");
printf("\n");
return 0;
}
BYU CS/ECEn 124
Arrays and Pointers
41
Function Pointers
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");
BYU CS/ECEn 124
Arrays and Pointers
42
Function Pointers
Complicated Declarations

C is sometimes castigated for the syntax of
declarations, particularly ones that involve pointers
to functions:
// f: function returning pointer to int
// pf: pointer to function returning int
int *f();
int (*pf)();

What do these do?
char **argv
int (*daytab)[13]
int *daytab[13]
char (*(*x())[])()
char (*(*x[3])())[5]
BYU CS/ECEn 124
argv: pointer to pointer to char
daytab: pointer to array[13] of int
daytab: array[13] of pointer to int
x: function returning pointer to array[ ] of
pointers to function returning char
x: array[3] of pointer to function returning
pointer to array[5] of char
Arrays and Pointers
43
BYU CS/ECEn 124
Arrays and Pointers
44