Array Assignments in C Using Pointer Arithmetic

廉价感情. 提交于 2019-12-11 04:42:36

问题


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;
}

回答1:


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.




回答2:


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

Simple:

a[1]++;

if you just wanted to increment a[1] (1) to be what b[1] happens to be (2), or

a[1] = b[1];

if you want a[1] to have the same value as b[1] regardless of what that value is.

when I access a particular element using pointer arithmetic?

In your example, you are not accessing any element, nor are you doing pointer arithmetic because a and b are arrays, not pointers. The formulation of your question is difficult to interpret, both because of that and because

a++ = b++;

1) is completely meaningless 2) would not be legal C even if a and b were pointers, because the left side must be an lvalue, but a++ is not 3) is not discernably related to your wish for a[1] to be the same as b[1]. Possibly what you want is:

int* ap = a; // get pointer to first element of a
int* bp = b; // get pointer to first element of b

// point ap to second element of a and
// point bp to second element of b and
// copy the value at *bp to *ap
*++ap = *++bp;

That would indeed set a[1] to b[1].




回答3:


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:

int *ap = a, *bp = b;

*ap++ = *bp++;

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:

*++ap = *++bp;

Or you could just use the array indices and make it much more obvious what you're doing.



来源:https://stackoverflow.com/questions/15468580/array-assignments-in-c-using-pointer-arithmetic

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!