Search code examples
carrayspointerspointer-arithmetic

Array Assignments in C Using Pointer Arithmetic


How can I change the value in an array when I access a particular element using pointer arithmetic?

#include <stdio.h>

int main() {
  int a[3] = {1, 1, 1}, b[3] = {2, 2, 2};

  a++ = b++; // How can I get this to work so a[1] = b[1]?

  return 0;
}

Solution

  • Arrays are not pointers. Repeat this three times; arrays are not pointers.

    You cannot increment an array, it is not an assignable value (i.e., you cannot mutate it). You can of course index into it to get a value back:

    a[1] = b[1];
    

    Secondly, your current code is attempting to increment and then assign a new value to the array itself, when you meant to assign to an element of the array. Arrays degrade to pointers when required, so this works too:

    int *a_ptr = a;
    int *b_ptr = b;
    *++a_ptr = *++b_ptr;
    // or, better...
    a_ptr[1] = b_ptr[1];
    

    Which is what you meant to do. I prefer version 1 and, more often than not, use indexing with pointers as well because it is often easier to read.