Académique Documents
Professionnel Documents
Culture Documents
Principles of Programming in C
Reza Azimi
Variable Declaration
int number;
number 0x18879A5B
Name
Memory Space What happens to the name number after the program is compiled? The compiler translates: number address
>=
yromem ni
3
61
smetsyS tib-46 rof )1- 462( FFFF FFFF FFFF FFFF )1- 232(
A multi-byte unit of memory address is called word, which is usually 4 bytes.
01552
=
61FF
ot 0 morf segnar
61
.0
number 0x18879A5B
ot stniop
p
18
87
9A
5B
p = &i; j = *p; j
content of (pointer dereferencing)
i=?, j=?
*p = 50;
5
Typed Pointers
int *p; double *q; char *r; int i; p q i r = = = = &i; &i; *p; *p; /* points only to integers */ /* points only to doubles */ /* points only to characters */
/* /* /* /*
k=?, j=?
8
A Common Mistake
int k, j, *p, *q; k = 100; j = 50; q = k; *q = 10;
Compiler may give you only a warning! Software may crash as a result.
t
sserdda .ter
&x (k) . . .
11
Pass by Reference
void max_min(int a[], int n, int *max, int *min) { max_min from p 250 int j; Call Stack *max = a[0]; *min = a[0]; for (j = 1; j < n; j++) { if (a[j] > *max) *max = a[j]; max else if (a[j] < *min) min *min = a[j]; } } int main(void) { int b[N], big, small; big max_min(b, N, &big, &small);
small
21
int main() { double number1 = 10.5, number2 = 7.5, avg; printf(Enter the two numbers: \n); scanf(%lf %lf, &number1, &number2); avg = weird_avg(number1, number2); printf(%g %g %g \n, number1, number2, avg); ...
31
Pointers as Arguments
double weird_avg(double *x, double *y) { *x = *x + *y; return *x / 2; }
Side Effect
51
Returning Pointers
int *max(int *a, int *b) { int k; Whats wrong with if (*a > *b) this program? k = *a; else Never return a k = *b; pointer to a local return &k; variable! } int *p, i, j; p = max(&i, &j);
printf(%d\n, *p);
71