Вы находитесь на странице: 1из 19

Arrays and Pointers

Arrays

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

BYU CS 224 Pointers and Arrays 3


Arrays

Initialization of Arrays
Elements can be initialized when they are declared in the
same way as local and global 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}};
Arays must be statically declared.
void SomeFunction(int num_elements)
{
int temp[num_elements]; // error
}

BYU CS 224 Pointers and Arrays 4


Arrays

Local Array Example


SP x 0x0014(SP)
int main() array[9] 0x0012(SP)
array[8] 0x0010(SP)
{ array[7] 0x000e(SP)
int array[10]; array[6] 0x000c(SP)
array[5] 0x000a(SP)
int x; array[4] 0x0008(SP)
for (x = 0; x < 10; x++) array[3] 0x0006(SP)
array[2] 0x0004(SP)
{ array[1] 0x0002(SP)
array[x] = x; SP
array[0] 0x0000(SP)
main:
} 0x8040: 8031 0016 SUB.W #0x0016,SP
return 0; 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
BYU CS 224 Pointers and Arrays 5
C Strings

C Strings
A C string is an array of characters, terminated with a zero byte.
C strings can be initialized when defined:
char outputString[] = "Cow";
same as:
outputString[0] = 'C'; Compiler computes
outputString[1] = 'o'; the size of the array
outputString[2] = 'w';
outputString[3] = 0;
(3 + 1 = 4 bytes)

Since arrays are not data types, C has no string operators.


There is no boundary checking in C.
int array[10], i;
for (i = 0; i <= 10; i++)
{
array[i] = 0;
}
BYU CS 224 Pointers and Arrays 7
Array Arguments

Passing Arrays as Arguments


C passes parameters to functions by reference.
C passes the address of the 1st element of an array.

#define MAX_NUMS 5
int average(int values[]) 0x05e8
{ SP values 0x05ea 0x05f2
int i, sum = 0; i 0x05ec 5
for (i = 0; i < MAX_NUMS; i++) sum 0x05ee 15
sum = sum + values[i];
0x05f0 Return Adr
return (sum / MAX_NUMS);
} SP nums[0] 0x05f2 1
nums[1] 0x05f4 2
int main() nums[2] 0x05f6 3
{ nums[3] 0x05f8 4
int nums[MAX_NUMS] =
{ 1, 2, 3, 4, 5 }; nums[4] 0x05fa 5
int mean = average(nums); mean 0x05fc 3
return 0; 0x05fe Return Adr
} 0x0600

BYU CS 224 Pointers and Arrays 8


Pointers
Pointers

Swap Function Example

int main() Stack after call to swap():


{
int a = 3; 0x05ea
int b = 4; 0x05ec
swap(a, b); 0x05ee

} 0x05f0
a 0x05f2 4
b 0x05f4 3
void swap(int a, int b) swap
temp 0x05f6 3
{ 0x05f8 Return Adr
int temp = a; a 0x05fa 3

a = b; main b 0x05fc 4

b = temp; 0x05fe Return Adr


0x0600
}

BYU CS 224 Pointers and Arrays 11


Pointers

Pointers int* ptr;


char* cp;
double* dp;
A pointer is an address int** p_ptr = &ptr;
char *strings[10];
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.

BYU CS 224 Pointers and Arrays 12


Pointers

Pointer Operators
A pointer variable is declared with the asterisk operator (*)
type *var; // same - whitespace doesnt matter
type* var;
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 224 Pointers and Arrays 13


Pointers

Operator Precedence and Associativity


* =dereference
& = reference
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
BYU CS 224 Pointers and Arrays 14
Pointers

Examples of Pointers
0x05ea
int *ptr1;
0x05ec
int *ptr2; 0x05ee
int **ptr3; 0x05f0
int i = 4; 0x05f2
int j; ptr1 0x05f4 0x05fa
ptr1 = &i; ptr2 0x05f6 0x05fc
ptr2 = &j; ptr3 0x05f8 0x05f4
ptr3 = &ptr1; i 0x05fa 4
j 0x05fc 4
0x05fe Return Adr
printf("%04x", ptr1); 05fa 0x0600
printf("%04x", ptr2); 05fc
printf("%04x", *ptr1); 0004
printf("%04x", *ptr2); ????
j = *ptr1;
printf("%04x", j); 0004
printf("%04x %04x", *ptr3, **ptr3); 05fa 0004

BYU CS 224 Pointers and Arrays 15


Swap Example w/Pointers

Swap Example Fixed!


Stack after call to swap()
int main() 0x05ea
{ 0x05ec

int a = 3; 0x05ee

int b = 4; 0x05f0
a 0x05f2 0x05fa
swap(&a, &b);
b 0x05f4 0x05fc
} swap
temp 0x05f6 3
0x05f8 Return Adr
void swap(int* a, int* b) a 0x05fa 3 4
{ main b 0x05fc 4 3
int temp = *a; 0x05fe Return Adr
0x0600
*a = *b;
*b = temp;
}

BYU CS 224 Pointers and Arrays 16


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 224 Pointers and Arrays 17


Pointer Arithmetic
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 (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]; Allocates 40 bytes
(4 per element)
double *y = x;
*(y + 3) = 13;
Same as x[3]
y++; (base address plus 12)
*y = 3.1415926;
x[1] = 3.1415926

BYU CS 224 Pointers and Arrays 19


Parsing

String Parsing
1. What is the value of X?
char str[] = "Point X = 100";
Walk the array until token
or NULL terminator.
2. Find token: (Token must be unique)
char* ptr = str;
int number = 0;
while (*ptr && (*ptr++ != 'X'));

3. Find beginning of number:


while (*ptr && !isdigit(*ptr)) ++ptr;

4. Convert to decimal:
isdigit returns 0 or 1
while (isdigit(*ptr))
number = number * 10 + (*ptr++ - '0');

5. Proceed with parsing of line. Return result in number

BYU CS 224 Pointers and Arrays 23


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"; a: h e l l o \0


char *p = "world";
p: w o r l d \0

BYU CS 224 Pointers and Arrays 24


Arrays and Pointers

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:


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]

BYU CS 224 Pointers and Arrays 25