添加整数C ++中的数组? [英] Adding integers to arrays in C++?
问题描述
考虑:
INT总和(const int的号码[],const int的大小){
如果(大小== 0)
返回0;
其他
返回号码[0] +总和(号码+ 1,尺寸-1);
}
这是从MIT 6.096一个简单的递归函数添加整数任意数量的,和它的作品。
我不明白的事情是在最后一行:
如何数字+ 1
工作,因为号码[]
是 INT
数组,你不应该能够为整数添加到 INT []
常数?
如何数字+ 1的工作,给定数字[]是一个int数组,你不应该能够为整数添加到一个int []常数?
块引用>有没有的
INT []
恒的。数字
腐朽的指针和数字+ 1
是用于传递给递归调用的参数简单的指针算术。Consider:
int sum(const int numbers[], const int size){ if (size == 0) return 0; else return numbers[0] + sum(numbers+1, size-1); }
This is a simple recursive function from MIT 6.096 for adding an arbitrary number of integers, and it works.
The thing I cannot understand is in the last line:
How does
numbers+1
work, givennumbers[]
is anint
array and you shouldn't be able to add an integer to anint[]
constant?解决方案how does "numbers+1" work, given numbers[] is an int array and you shouldn't be able to add an integer to an int[] constant?
There's no
int[]
constant.numbers
is decayed to a pointer andnumbers+1
is simple pointer arithmetic applied to the parameter passed to the recursive call.这篇关于添加整数C ++中的数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!