Modifying elements of an array through a pointer to its elements

92 views Asked by At

Given the code:

int vector[5] = {1, 2, 3, 4, 5};
int *pv = vector, value = 3;

for(int i = 0; i < 5; i++) {
    *pv++ *= value;
}

for(int i = 0; i < 5; i++) {
    printf("%d, ", *(pv+i));
}

I expect each individual element of the array pointed to by pv to be multiplied by 3. Instead what I get as an output is:

32766, -1554513907, -527290408, -333409024, 32766, 

What am I doing wrong?

2

There are 2 answers

4
anastaciu On BEST ANSWER

The problem is that you incremented the pointer in the first for cycle in every loop, so when you get to the end of it, pv is already pointing to one past the end of vector.

For that reason all the values printed in the second for cycle represent residual values stored in addresses out of the bounds of the array, classic undefined behavior.

A quick fix would be to reset the pointer in between the two cycles:

for (int i = 0; i < 5; i++){
    *pv++ *= value;
}

pv = vector; //here

for (int i = 0; i < 5; i++) {
    printf("%d, ", *(pv + i));
}

Or use the iterator i in both cycles, since you already have it in the for, you might as well use it:

for (int i = 0; i < 5; i++){
    pv[i] *= value;
}

for (int i = 0; i < 5; i++) {
    printf("%d, ", pv[i]); 
}

With this method the pointer is not incremented, it's always pointing to the beginning of the array, accessing its indexes is safe.

Note that I used array notation [] as it's slightly less cluttered than the pointer dereference notation.

0
Allan On

In your program, the first for loop (ie)

for(int i = 0; i < 5; i++) {
    *pv++ *= value;
}

Here, pointer(pv) gets incremented for 5 times and when the control exits the loop , pointer(pv) is now pointing to something which is out-of-bounds of your array size(vector) Since you're using the same pointer variable in second for loop to print the array(vector) values, the garbage values gets printed.

You can solve this by reassigning your pointer variable(pv) back to the 1st position of your array either by

pv= vector;

// or

pv = &vector[0];

before your second for loop.