OOP3 N
OOP3 N
Address Arithmetic
• Address of operator &
The value of an expression &x is an address
• Other expressions yield addresses
– the name of an array, written without brackets
– the address is that of the first element of the array
char s[50];
s is equivalent to &(s[0])
– we can combine the name of an array with integers
s is equivalent to &(s[0])
s+i is equivalent to &(s[i])
1 of 53.
2 of 53.
*a is equivalent to a[0]
*(a+i) is equivalent to a[i]
3 of 53.
4 of 53.
#include <iostream.h>
int main()
{ int table[10], minimum(int *a, int n);
cout << “Enter 10 integers: \n”;
for (int i=0; i<10; i++) cin >> table[i];
cout << “\nThe minimum of these values is “
<< minimum(table, 10) << endl;
return 0;
}
5 of 53.
6 of 53.
7 of 53.
p= &n;
k = *p // k is now equal to???
int main()
{ char *p, ch;
*p = ‘A’; // Serious error!
return 0;
}
9 of 53.
int main()
{ char *p, ch;
p = &ch;
*p = ‘A’;
return 0;
}
10 of 53.
11 of 53.
12 of 53.
13 of 53.
14 of 53.
15 of 53.
16 of 53.
17 of 53.
18 of 53.
char s[4];
20 of 53.
int main()
{ char s[100]=“Program something.”, t[100];
strcpy(t, s);
strcpy(t+8, “in C++.”;
cout << s << endl << t << endl;
return 0;
} // what is the output?
21 of 53.
22 of 53.
23 of 53.
24 of 53.
25 of 53.
26 of 53.
int main()
{ char *p;
set_new_handler(0); // required with Borland C++
for (int i=1;;i++) // horrible style
{ p = new char[10000];
if (p == 0) break;
cout << “Allocated: “ << 10 * i << “kB\n”;
}
return 0;
} // rewrite this in a better style!
27 of 53.
28 of 53.
#include <stdlib.h>
int n;
char *s;
...
cin > n;
s = (char *) malloc (n);
29 of 53.
#include <stdlib.h>
int n;
float *f;
...
cin > n;
s = (float *) malloc (n * sizeof(float));
30 of 53.
31 of 53.
32 of 53.
– free(s);
33 of 53.
34 of 53.
35 of 53.
36 of 53.
int main()
{ char *p[3] = {“Charles”, “Tim”, “Peter”};
int age[3] = {21, 5, 12}, i;
for (i=0; i<3; i++)
printf(“%-12s%3d\n”, p[i], age[i]); // left align
return 0;
}
37 of 53.
39 of 53.
40 of 53.
f(table);
return 0;
}
int f(float t[][5]) // may omit the first dimension
{ // but all other dimensions must
} // be declared since it must be
// possible to compute the
// address of each element. How?
41 of 53.
Table[2][3]
dtable
dtable[2][3]
44 of 53.
45 of 53.
argv
Program name
argc = 4 A B C \0
P Q \0
X Y Z \0
46 of 53.
47 of 53.
#include <stdio.h>
...
char s[50]=“123 456 \n98.756”;
int i, j;
double x;
sscanf(s, “%d %d %lf”, &i, &j, &x);
#include <stdio.h>
...
char s[50]=“123 456 \n98.756”;
sprintf(s,“Sum: %6.3f Difference:%6.3f”,
45 + 2.89, 45 - 2.89);
49 of 53.
// function definition
float example (int i, int j)
{ return 3.14159 * i + j;
}
50 of 53.
p(12, 34); // !!
51 of 53.
52 of 53.