Help me with Pointers!

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:

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
27
28
char charA[6] = "HELLO";
int intA[] = {2,4,3,8,7};
char *ptrA;
int *ptrB, *ptrC;

ptrA = &charA[4];
ptrB = intA;
ptrC = new int [5];

for(int i = 4; i >= 4; i--)
{
 *ptrC = (intA[i]) + (*ptrB) + 1;
 cout << *ptrC << " " << *ptrB << " ";
 ptrB++; 
 ptrC++;
}
cout << endl;
ptrB--;
ptrC--;

for(int i = 0; i < 5; i++)
{
 cout << (*ptrC + *ptrB) << " " << *ptrA << endl;
 ptrC--;
 ptrA--;
 ptrB--;
}
   


I only understand the upper part of this code but the rest look so confusing to me. Any help would be appreciated.

-cplusx2
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). 
Last edited on
A pointer is a variable. The value is the address of something else.

If it's a pointer to an int, it will hold the address of an int or nothing (NULL).
1
2
int a = 8;
int *intptr = &a;

If you increment a pointer to an int, it will point to the next int in the sequence.
1
2
3
int array[] = { 7, 8, 9 };
int *intptr = &array;
intptr++; // or ++intptr; 

You can look at what a pointer is pointing to by dereferencing it.
1
2
3
int array[] = { 7, 8, 9 };
int *intptr = &array;
int value = *intptr

Gonna take a guess and say line 10.

for(int i = 4; i >= 4; i--)


Should be i >= 0.

Since otherwise this prints nonsense.
Topic archived. No new replies allowed.