Can anyone help me with pointers? I can't understand it very well. Anyway, I was given an assignment to trace the output of this program without using any compiler:
Pointers and arrays are quite alike:
myArray[t] accesses the (t+1)th element of myArray. Behind the screens, however, it takes the address stored in "myArray" and increments it by t*sizeof(type). As a result, these two things are the same:
1 2
myArray[t] = 6;
*(myArray+t = 6;
In the same way, you can also walk through an array by pointers rather than by index. Take these examples:
1 2 3 4 5 6 7 8
int myArray = {2, 4, 6, 8, 10};
// By index
for (int t = 0; t < 5; ++t) cout << myArray[t] << endl;
// By offset (name?)
for (int t = 0; t < 5; ++t) cout << *(myArray+t) << endl;
// By pointer
int *ptr = myArray;
for (int t = 0; t < 5; ++t) cout << *(ptr++) << endl;
The three loops do the exact same, but in a (code-wise) different way.
Do mind, when using pointer-type access and arithmetic, that these things are not the same:
1 2
cout << *(ptr++); // Prints the value, increments the pointer.
cout << (*ptr)++; // Prints the value, increments the value (thus changing the element).