Developer working at a desk with code on the monitor
Photo by Kelly Sikkema on Unsplash

Programming

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.

Array a2
Index012345
Value123456

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.

Array a before and after memcpy
Index01234567891011
Before111111111111
After111100111111

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].

From the course

  • Semesters 2 and 3
  • Lab works in C and C++

Useful resources

  1. Beginning C++17 : From Novice to Professional e-book in the TSI library, a TSI account is required
  2. C++ Tutorials well known tutorial website
  3. C++ another online reference
  4. DariaEmacs inspiring YouTube channel about C++