|
1 | 1 | /**
|
2 | 2 | * Pointer operators precedence
|
| 3 | + * ============================ |
3 | 4 | */
|
4 | 5 |
|
5 |
| -#include <stdio.h> |
6 |
| -#include <stdlib.h> |
| 6 | +#include "tests.h" |
7 | 7 |
|
8 |
| -void print_a(int *a, int n) |
| 8 | +/* =========================================================================== |
| 9 | + * Algorithms implementation |
| 10 | + * =========================================================================== |
| 11 | + */ |
| 12 | +#define _fmt(i, v) format("\n index: {}, value: {}", i, v) |
| 13 | + |
| 14 | +vi_t ptrOpPrec(const int n, string &am) |
9 | 15 | {
|
10 |
| - printf("a: "); |
11 |
| - for (int i = 0; i < n; i++) { printf("%d ", a[i]); } |
| 16 | + int *p = (int *)malloc(n * sizeof(int)), *a = p; |
| 17 | + fii (i, n) *(p + i) = i; |
| 18 | + |
| 19 | + ostringstream out; |
| 20 | + out << _fmt(0, *p++); // *a -> index: 0, value: 0, ptr++ |
| 21 | + out << _fmt(1, (*p)++); // *a -> index: 1, value: 1, val++ |
| 22 | + out << _fmt(1, *p); // *a -> index: 1, value: 2 |
| 23 | + out << _fmt(2, *++p); // *a -> index: 2, value: 2, ++ptr |
| 24 | + out << _fmt(2, ++*p); // *a -> index: 2, value: 3, ++val |
| 25 | + // indices: 3, 4 with values: 3, 4 are unmodified |
| 26 | + vi_t ret(a, a + n); |
| 27 | + out << format("\n after: {}", to_string(ret)); |
| 28 | + free(a); |
| 29 | + am = out.str(); |
| 30 | + return ret; |
12 | 31 | }
|
13 | 32 |
|
14 |
| -int main(int argc, char *argv[]) |
| 33 | +/* =========================================================================== |
| 34 | + * Test code |
| 35 | + * =========================================================================== |
| 36 | + */ |
| 37 | +TEST(ptrOpPrec, "Pointer operators precedence") |
15 | 38 | {
|
16 |
| - int *ptr = (int *)malloc(5 * sizeof(int)); |
17 |
| - int *p = ptr; |
18 |
| - for (int i = 0; i < 5; i++) *(ptr + i) = i; |
19 |
| - print_a(p, 5); |
20 |
| - printf("\tp: %d\n", *ptr++); // ptr -> index: 0, value: 0, ptr++ |
21 |
| - print_a(p, 5); |
22 |
| - printf("\tp: %d\n", (*ptr)++); // ptr -> index: 1, value: 1, val++ |
23 |
| - print_a(p, 5); |
24 |
| - printf("\tp: %d\n", *ptr); // ptr -> index: 1, value: 2 |
25 |
| - print_a(p, 5); |
26 |
| - printf("\tp: %d\n", *++ptr); // ptr -> index: 2, value: 2, ++ptr |
27 |
| - print_a(p, 5); |
28 |
| - printf("\tp: %d\n", ++*ptr); // ptr -> index: 2, value: 3, ++val |
29 |
| - print_a(p, 5); // indices: 3, 4 with values: 3, 4 are unmodified |
30 |
| - printf("\n"); |
31 |
| - free(p); |
32 |
| - return 0; |
| 39 | + const int n = 5; |
| 40 | + string am; |
| 41 | + vi_t e = {0, 2, 3, 3, 4}; |
| 42 | + vi_t a = ptrOpPrec(n, am); |
| 43 | + CHECK_EQ(e, a); |
| 44 | + SHOW_OUTPUT(n, am); |
33 | 45 | }
|
| 46 | + |
| 47 | +INIT_TEST_MAIN(); |
0 commit comments