Pointers questions
What is a3 equal to?
int main() {
int a2[] = {1, 2, 3, 4, 5, 6};
int a3 = (1 + 3)[a2] - a2[0]
+ (a2 + 1)[2];
}
Show the answer
a3 is 8.
| Index | 0 | 1 | 2 | 3 | 4 | 5 |
|---|---|---|---|---|---|---|
| Value | 1 | 2 | 3 | 4 | 5 | 6 |
The index operator x[y] means *(x + y), so the operands can be swapped: (1 + 3)[a2] is a2[4], that is 5; a2[0] is 1; (a2 + 1)[2] is a2[3], that is 4. The result is 5 − 1 + 4 = 8.
What will the following program output to the console, if int takes 4 bytes and long long takes 8 bytes:
#include <cstring>
#include <iostream>
int main(){
int a[]= {1,1,1,1, 1,1,1,1,
1,1,1,1};
long long zero = 0;
char *p = (char *)a;
p += 2 * sizeof zero;
std::memcpy(p, &zero,
sizeof zero);
for(int i = 0; i < 12; i++) {
std::cout << (int)a[i]
<< " ";
}
}
Show the answer
The program prints 1 1 1 1 0 0 1 1 1 1 1 1.
| Index | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
| Before | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 |
| After | 1 | 1 | 1 | 1 | 0 | 0 | 1 | 1 | 1 | 1 | 1 | 1 |
The pointer p looks at the array byte by byte. It moves 2 · sizeof zero = 16 bytes forward: four elements of 4 bytes, to a[4]. memcpy writes 8 zero bytes there, and they cover two elements: a[4] and a[5].