C 9
C 9
Array
– A consecutive series of variables that share one name
int num[5] ;
num
2
The Relationship between Arrays and
Pointers
Example :
– Which address does each element have?
&num[0] == 1000
&num[1] == 1004 1000 1004 1008 1012 1016
&num[2] == 1008 Memory addresses
&num[3] == 1012
&num[4] == 1016
3
The Relationship between Arrays and
Pointers
Example : What is num?
4
The Relationship between Arrays and
Pointers
Example : Arithmetic of pointers
– “pointer + 1” does not mean increasing pointer by 1.
– “pointer + 1” is “the address of the next element”.
– “pointer – 1” is “the address of the prior element”.
5
The Relationship between Arrays and
Pointers
Example : Arithmetic of pointers
int num[5] ; int num[5] ; int num[5], *p = num ; int num[5], *p = num ;
int num[5] ; 10 20 30 40 50
6
Pointer Arithmetic and Element Size
Adding an Integer to a Pointer
p
[Ex] a
p = &a[2];
0 1 2 3 4 5 6 7 8 9
p q
q = p + 3; a
0 1 2 3 4 5 6 7 8 9
q p
p += 6; a
0 1 2 3 4 5 6 7 8 9
7
Pointer Arithmetic and Element Size
Subtracting an Integer from a Pointer
p
[Ex] a
p = &a[8];
0 1 2 3 4 5 6 7 8 9
q p
q = p - 3; a
0 1 2 3 4 5 6 7 8 9
p q
p -= 6; a
0 1 2 3 4 5 6 7 8 9
8
Pointer Arithmetic and Element Size
Subtracting Pointers
[Ex]
p = &a[5];
q = &a[1];
i = p – q; /* i == 4 */
i = q – p; /* i == -4 */
q p
a
0 1 2 3 4 5 6 7 8 9
9
Pointer Arithmetic and Element Size
Comparing Pointers
– Relational operators (<, <=, >, >=) can be applied
– Equality operators (==, !=) can be applied
[Ex]
p = &a[5];
q = &a[1];
p <= q; /* result is 0 */
p >= q; /* result is 1 */
10
Pointer Arithmetic and Element Size
Example: Pointer Operation
int a[ ] = { 5,15,25,43,12,1,7,89,32,11}
int *p = &a[1], *q = &a[5] ;
1. *(p + 3) ?
2. *(q - 2) ?
3. q - p ?
4. if ( p > q ) ?
5. if ( *p > *q )?
11
Pointer Arithmetic and Element Size
Example: Pointer Operation
#include <stdio.h>
int main(void)
{
double a[2], *p, *q;
p = &a[0]; /* points at base of array */
q = p + 1; /* equivalent to q = &a[1]; */
printf(“%d\n”, q – p );
printf(“%d\n”, (int) q – (int) p );
printf(“%d\n”, sizeof(double) );
return 0;
}
12
Combining the * and ++ Operators
Combining the * and ++ Operators
(*p)++, (*p)--
13
Combining the * and ++ Operators
Combining the * and ++ Operators
14
Combining the * and ++ Operators
Combining the * and ++ Operators
15
Example
int num[] and int *num
are the same
Add inputted integer numbers
#include <stdio.h> #include <stdio.h>
int sum( int num[], int size ) { int sum( int num[], int size ) {
int k, sum = 0 ; int k, sum = 0 ;
for( k = 0 ; k < size ; k++ ) for( k = 0 ; k < size ; k++ )
sum += num[k] ; sum += *num++ ;
return sum ; return sum ;
} }