Array and Pointers
Array and Pointers
Arrays in C
No bounds checking!
Allowed – usually causes no obvious error
array[10] may overwrite b
Array Representation
Homogeneous ® Each element same size – s bytes
w An array of m data values is a sequence of m´s bytes
w Indexing: 0th value at byte s´0, 1st value at byte s´1, …
0x1008 a[2]
0x1004 a[1] int a[3];
0x1000 a[0]
Array Representation
char c1;
int a[3];
char c2;
int i;
0x1014 i
0x1010 c2
0x100C a[2]
Could be optimized by
a[1] making these adjacent,
0x1008 and reducing padding
a[0] (by default, not)
0x1004
0x1000 c1
Array aligned by
size of elements
Array Sizes
int array[10];
What is
sizeof(array[3])? 4
returns the size of
an object in bytes
sizeof(array)? 40
Multi-Dimensional Arrays
0x1014 matrix[1][2]
0x1010 matrix[1][1]
int matrix[2][3];
0x100C matrix[1][0]
matrix[0][3] = 42;
Variable-Length Arrays
int
function(int n)
{
int array[n];
…
Variable-length arrays
defined within functions
int *ptr;
Creation
& variable Returns variable’s memory address
Dereference
* pointer Returns contents stored at address
Indirect assignment
* pointer = val Stores value at address
Assignment
pointer = ptr Stores pointer in another variable
Using Pointers
int i1;
int i2;
int *ptr1; 0x1014 … 0x1000
int *ptr2;
0x1010 ptr2:
i1 = 1; 0x100C … 0x1000
i2 = 2;
0x1008 ptr1:
*ptr1 = 3;
i2 = *ptr2;
Using Pointers (cont.)
int int1 = 1036; /* some data to point to */
int int2 = 8;
*int_ptr1 = int_ptr2;
*int_ptr1 = int2;
What happens?
int1 becomes 8
Using Pointers (cont.)
int int1 = 1036; /* some data to point to */
int int2 = 8;
int_ptr1 = *int_ptr2;
int_ptr1 = int_ptr2;
What happens?
p = &a; p = &a;
p += 1; In each, p now points to b p += 1;
(Assuming compiler doesn’t
reorder variables in memory)
void
set_x_and_y(int *x, int *y)
{
*x = 1001;
*y = 1002; a 1001
1
}
b 1002
2
void
f(void)
{ x
int a = 1;
int b = 2; y
set_x_and_y(&a, &b);
}
Arrays and Pointers
Dirty “secret”: Passing arrays:
Array name » a pointer to the Must explicitly
Really int *array pass the size
initial (0th) array element
int
foo(int array[],
a[i] º *(a + i) unsigned int size)
{
An array is passed to a function … array[size - 1] …
as a pointer }
w The array size is lost!
int
main(void)
Usually bad style to interchange {
arrays and pointers int a[10], b[5];
w Avoid pointer arithmetic! … foo(a, 10)… foo(b, 5) …
}
Arrays and Pointers
int
foo(int array[],
unsigned int size)
{
… What does this print? 8
printf(“%d\n”, sizeof(array));
}
... because array is really
a pointer
int
main(void)
{
int a[10], b[5];
… foo(a, 10)… foo(b, 5) … What does this print? 40
printf(“%d\n”, sizeof(a));
}
Arrays and Pointers
C, … H e l l o , w o r l d ! \n terminator
C terminator: ’\0’
“ 3”