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;
}
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:
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:
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.
Your arrays in this case are not actually pointers. They are converted by the compiler when they are accessed as pointers, but I don't believe that you're allowed to do something like
a++
.If you want to do this with arithmetic, you'll need actual pointers:
That is like doing
a[0] = b[0];
and then moving each pointer to the next element in their associated array.But your question says you want to set
a[1] = b[1]
. Well, you could do this:Or you could just use the array indices and make it much more obvious what you're doing.
Simple:
if you just wanted to increment
a[1]
(1) to be whatb[1]
happens to be (2), orif you want
a[1]
to have the same value asb[1]
regardless of what that value is.In your example, you are not accessing any element, nor are you doing pointer arithmetic because
a
andb
are arrays, not pointers. The formulation of your question is difficult to interpret, both because of that and because1) is completely meaningless 2) would not be legal C even if
a
andb
were pointers, because the left side must be an lvalue, buta++
is not 3) is not discernably related to your wish fora[1]
to be the same asb[1]
. Possibly what you want is:That would indeed set
a[1]
tob[1]
.