的sizeof()一个C ++阵列上工作在一个功能,而不是在其他 [英] Sizeof() on a C++ array works in one function, but not in the other

查看:102
本文介绍了的sizeof()一个C ++阵列上工作在一个功能,而不是在其他的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想更多地了解阵列,因为我是新来编程。所以我是用code的不同部位发挥,并试图了解三件事,的sizeof()。如何找到一个数组的长度,还怎么做我把数组转换功能(作为一个参数)?

I'm trying to learn more about arrays since I'm new to programming. So I was playing with different parts of code and was trying to learn about three things, sizeof(). How do I find the length of an array, and also how do I put arrays into functions (as a parameter)?

我的code是:

#include <iostream>

using namespace std;

void arrayprint(int inarray[])
{
    for (int n_i = 0 ; n_i < (sizeof(inarray) / sizeof(int)) ; n_i++)
    {
        cout << inarray[n_i] << endl;
    }
}

int main()
{
    int n_array[5];
    for (int n_i = 0 ; n_i < (sizeof(n_array) / sizeof(int)) ; n_i++ )
    {
        cin >> n_array[n_i];
    }
    arrayprint(n_array);
    return 0;
}

看来的sizeof(inarray)/的sizeof(INT)工程的主要功能,但不是在arrayprint功能。在阵列打印功能,它的计算结果为1,而在主要的计算结果为5.为什么?

It seems the sizeof(inarray) / sizeof(int) works in the main function, but not in the arrayprint function. In the array print function, it evaluates to 1, while in main it evaluates to 5. Why?

所以,我想我想知道的是如何不同?为什么?

So I guess what I want to know is how they are different? And why?

推荐答案

void arrayprint(int inarray[])

时相同的:

void arrayprint(int *inarray)

所以你得到一个int指针的大小你的机器上。即使你的问题是关于C ++和你的函数看起来有点不同,它归结为Ç常见问题解答项。

所以,在 n_array 实际上是一个真正诚实的数组。但传递给函数时,它衰变到一个指针。而且也没有办法知道真正的大小。所有你能做的就是通过额外的参数给你的函数。

So, inside main n_array is actually a true honest array. But when passed to a function, it "decays" into a pointer. And there's no way to know the real size. All you can do is pass additional arguments to your function.

void arrayprint(int inarray[], int len)
{
    for (int n_i = 0 ; n_i < len; n_i++)
    /* .... */

和调用它是这样的:

arrayprint(n_array, sizeof(n_array) / sizeof(n_array[0]));

当然,的真正的解决方案是使用矢量取值由于您使用C ++。但我不知道很多关于C ++。

Of course, the real solution would be to use vectors since you're using C++. But I wouldn't know much about C++.

这篇关于的sizeof()一个C ++阵列上工作在一个功能,而不是在其他的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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