C 使用指针向数组中的每个元素添加数字
有一个函数,我想给数组中的每个元素添加数字,只使用指针。但我失败了。主要的问题是如何加总。指针导致while循环出错C 使用指针向数组中的每个元素添加数字,c,pointers,C,Pointers,有一个函数,我想给数组中的每个元素添加数字,只使用指针。但我失败了。主要的问题是如何加总。指针导致while循环出错 void f(int *a, const int len) { const int *pointer = a; const int *add; while (pointer < a + len) { (a + pointer) += add; //this is like a[p], but with pointers, it's not work
void f(int *a, const int len) {
const int *pointer = a;
const int *add;
while (pointer < a + len) {
(a + pointer) += add; //this is like a[p], but with pointers, it's not working
++ pointer;
}
}
void f(int*a,const int len){
常量int*指针=a;
常数整数*加法;
while(指针
以下是原始代码,为使其正常工作,对其进行了最少的修改,并提供了一些注释来解释更改:
void f(int *a, const int len) {
const int add = 101; // must initialize `add` here, since it's `const` and can't be modified later
int *pointer = a; // initialize `pointer` to point to the first element in the array
// can not be `const int *` since `*pointer` must be writeable
while (pointer < a + len) {
*pointer += add; // add `add` to the current element that `pointer` points to
++pointer; // increment `pointer` to point to the next element
}
}
以下是原始代码,其中包含了使其正常工作所需的最小更正,以及解释更改的一些注释:
void f(int *a, const int len) {
const int add = 101; // must initialize `add` here, since it's `const` and can't be modified later
int *pointer = a; // initialize `pointer` to point to the first element in the array
// can not be `const int *` since `*pointer` must be writeable
while (pointer < a + len) {
*pointer += add; // add `add` to the current element that `pointer` points to
++pointer; // increment `pointer` to point to the next element
}
}
指针可以减,但我不确定它们是否可以加。让我来确认一下。是的,我是对的。看,指针可以减,但我不确定它们是否可以加。让我来确认一下。是的,我是对的。请参阅。我总是尝试在
之后进行注释,而(len--){
将/*循环len次*/
,因为对于新的C用户来说,这可能不会立即显现出来(尽管他们应该能够推断出这么多)@DavidC.Rankin很好的一点,我添加了几条注释。这是downto操作符的一个很好的候选者:while(len-->0){*ptr+++=101;}
哦,这几乎是残酷的:)
@chqrlie啊,当然。这是我们学习的核心语言功能之一,就在旁边;-)我总是在之后尝试和评论,而(len-){
它将/*循环len次*/
,因为对于新的C用户来说,这可能不会立即显现出来(虽然他们应该能够推断出同样多)@DavidC.Rankin很好的观点,我添加了一些评论。这是一个很好的下行操作符的候选:而(len-->0){*ptr++=101;}
哦,这几乎是残酷的:)
@chqrlie啊,当然了。这是我们学习的核心语言功能之一,就在;-)