将整数添加到 C++ 中的数组? [英] Adding integers to arrays in C++?

查看:37
本文介绍了将整数添加到 C++ 中的数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑:

int sum(const int numbers[], const int size){
    if (size == 0)
        return 0;
    else
        return numbers[0] + sum(numbers+1, size-1);
}

这是一个来自 MIT 6.096 的简单递归函数,用于添加任意数量的整数,并且有效.

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:

numbers+1 是如何工作的,给定 numbers[] 是一个 int 数组,你不应该能够添加一个整数到 int[] 常量?

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?

推荐答案

numbers+1"如何工作,给定 numbers[] 是一个 int 数组,并且您不应该将整数添加到 int[] 常量中?

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?

没有int[]常量.numbers 衰减为指针,numbers+1 是应用于传递给递归调用的参数的简单指针算法.

There's no int[] constant. numbers is decayed to a pointer and numbers+1 is simple pointer arithmetic applied to the parameter passed to the recursive call.

这篇关于将整数添加到 C++ 中的数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆