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

查看:200
本文介绍了添加整数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, given numbers[] is an int array and you shouldn't be able to add an integer to an int[] 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 and numbers+1 is simple pointer arithmetic applied to the parameter passed to the recursive call.

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

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