数组赋值在C使用指针运算 [英] Array Assignments in C Using Pointer Arithmetic
问题描述
我怎样才能改变一个数组的值,当我使用指针算法访问一个特定元素?
的#include<&stdio.h中GT;诠释主(){
诠释一个[3] = {1,1,1},B [3] = {2,2,2}; 一个++ = B ++; //我怎样才能得到这个工作,所以[1] = B [1]? 返回0;
}
数组不是指针。重复此三次;的数组不是指针的
您不能增加一个数组,它不是一个分配的值(即,可以发生变异的话)。当然你也可以索引到它得到一个值返回:
A [1] = B [1];
其次,当前的code试图递增,然后分配一个新值的阵列本身的,当你的意思是要分配给数组的元素。在需要时数组降解为指针,所以这个工程太:
为int * a_ptr = A;
为int * B_PTR = B;
* ++ a_ptr = * ++ B_PTR;
//或者更好的...
a_ptr [1] = B_PTR [1];
这就是你的意思做。我和,往往不是preFER版本1,使用索引的指针,以及因为它往往是更容易阅读。
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:
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.
这篇关于数组赋值在C使用指针运算的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!