Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!
Scott Rixner
Arrays and Pointers
No bounds checking! Allowed – usually causes no error array[10] may overwrite b
Array size in declaration must be constant
Compare:
int^
array[10]; Java:
int[10]
array;
All elements of same type – homogenous First element (index 0) Last element (index size - 1)
Scott Rixner
Arrays and Pointers
char
c1; int^
a[3]; char
c2; int^
i;
c
i a[2] a[1] a[0]
0x1014 0x100C0x10080x1004^ 0x
c 0x
Could be optimized bymaking these adjacent,and reducing padding(by default, not)^ Array aligned bysize of elements
Scott Rixner
Arrays and Pointers
What is sizeof(array[3])
?
sizeof(array)
?
int^
array[10];
(^440)
returns the size ofan object in bytes
Scott Rixner
Arrays and Pointers
int^
n^ =^
…; int^
array[n];
Scott Rixner
Arrays and Pointers
Elements in contiguous addresses, viewed as element
offsets from base of array
Usually smallest addressable unit of memory^ •^ Few machines can directly access bits individually Addresses also known as
byte-addresses
Most common size of addressable unit of memory When applicable, use
word-addresses
^ Word-address m = byte-address (m
×^ bytes/word)
Scott Rixner
Arrays and Pointers
variable
Returns variable’s memory address
pointer
Returns contents stored at address
pointer
=^ val
Stores value at address
=^ ptr
Stores pointer in another variable
Scott Rixner
Arrays and Pointers
ptr1: i2: i1: 0x10080x1004 0x
ptr2: 0x10140x10100x100C
0x10000x1000^2313
Scott Rixner
Arrays and Pointers
Type check warning:
*int_ptr
is not an
int
Changes
int_ptr
- doesn’t change
int
What happens?
Scott Rixner
Arrays and Pointers
+^ number
pointer
-^ number
E.g.,
pointer
+^1
adds 1 something
to a pointer
char^
*^ p; char^
a; char^
b; p^ =^ &a;p^ +=^
int^ *
p; int^
a; int^
b; p^ =^ &a;p^ +=^
In each, p now points to b(Assuming compiler doesn’treorder variables in memory)
Adds 1sizeof(char) tothe memory address*
Adds 1sizeof(int) tothe memory address*
Pointer arithmetic is usually
confusing and bad style
Scott Rixner
Arrays and Pointers
Reduces effectiveness of type-checking Can’t use pointer arithmetic
void^ Might find useful in last project
*^ p; int^
i; char^
c; p^ =^ (void
&i;
p^ =^ (void
&c;
type cast: tells the compiler to“change” an object’s type (for typechecking purposes – does not modifythe object in any way) Dangerous! Sometimes necessary…
Scott Rixner
Arrays and Pointers
Scott Rixner
Arrays and Pointers
i; int^
array[10]; for^
(i^ =^
0;^ i^
i++)
{^ array[i]
int^ *p;int^
array[10]; for^ (p
=^ array;
p^ <^
&array[10];
p++)
{ *p^
Scott Rixner
Arrays and Pointers
Terminated with ‘\0’ character Arrays for bounded-length strings Pointer for constant strings (or unknown length)
C terminator:
’\0’