Week 9: Pointer — Solution
Week 9: Pointer — Solution
Exercise Solutions
Exercise 1: Change multiple values in a function using pointers
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <stdio.h>
void addOne(int *a, int *b, int *c, int *d) {
(*a)++;
(*b)++;
(*c)++;
(*d)++;
}
int main(void) {
int a = 1, b = 2, c = 3, d = 4;
printf("=====before change=====\n");
printf("a = %d, b = %d, c = %d, d = %d\n", a, b, c, d);
addOne(&a, &b, &c, &d);
printf("=====after change=====\n");
printf("a = %d, b = %d, c = %d, d = %d\n", a, b, c, d);
return 0;
}
Example Output:
1
2
3
4
=====before change=====
a = 1, b = 2, c = 3, d = 4
=====after change=====
a = 2, b = 3, c = 4, d = 5
Exercise 2: Find the Maximum Value Using Pointers
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <stdio.h>
int main(void) {
int array[] = {3, 2, 4, 22, 15, 6, 8};
int n = sizeof(array) / sizeof(array[0]);
int *p = array;
int max = *p;
for (int i = 1; i < n; i++) {
if (*(p + i) > max) {
max = *(p + i);
}
}
printf("Maximum value = %d\n", max);
return 0;
}
Example Output:
1
Maximum value = 22
Exercise 3: Find an Alphabet in a Word (pointer arithmetic)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#include <stdio.h>
int main(void) {
char letter;
char word[100];
printf("Please input the alphabet you want: ");
scanf(" %c", &letter);
printf("Please input the word you want: ");
scanf("%s", word);
char *p = word;
int found = 0;
while (*p != '\0') {
if (*p == letter) {
found = 1;
break;
}
p++;
}
if (found) printf("found %c!\n", letter);
else printf("cannot find %c!\n", letter);
return 0;
}
Example Output:
1
2
3
Please input the alphabet you want: i
Please input the word you want: apple
cannot find i!
1
2
3
Please input the alphabet you want: a
Please input the word you want: grammer
found a!
This post is licensed under CC BY 4.0 by the author.