Search code examples
arrayscpointerspointer-to-array

Modifying elements of an array through a pointer to its elements


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?


Solution

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