数组的C ++大小 [英] Size of an array C++

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

问题描述


  

可能重复:结果
  的sizeof数组作为参数传递


我想知道为什么下面的code的输出为1和9是因为功能未申报大小的数组的?我怎样才能数组大小分开,一个功能?

 的#includestdafx.h中
#包括LT&;&iostream的GT;
使用命名空间std;INT尺寸(int类型的[])
{
    返回的sizeof一个/ sizeof的一个[0];
}诠释的main()
{
    诠释一个[] = {} 5,2,4,7,1,8,9,10,6;
    COUT<<大小(一)LT;< ENDL;
    COUT<< sizeof的一个/ sizeof的一个[0]&下;&下; ENDL;
    系统(暂停);
    返回0;
}


解决方案

当你写尺寸(A)然后你传递一个指针,而不是一个数组。由于指针的大小和 INT 为4或8个(根据ABI),您将获得的sizeof(INT *)/ sizeof的INT 4月4日= 1 作为32位的机器和 8/4 = 2 作为64位的)这就是 1 2

在C ++中,当传递一个数组作为参数传递给一个函数,其实你传递一个指针数组。

Possible Duplicate:
Sizeof array passed as parameter

I was wondering why the output of the following code is 1 and 9. Is that because of undeclared array in function size? How can I separate "size of array" to a function?

#include "stdafx.h"
#include <iostream>
using namespace std;

int size(int a[])
{
    return sizeof a/sizeof a[0];
}

int main()
{   
    int a[] = {5,2,4,7,1,8,9,10,6};
    cout << size(a) << endl;
    cout << sizeof a/sizeof a[0] << endl;
    system("pause");
    return 0;
}

解决方案

When you write size(a) then you're passing a pointer and not an array. Since the size of a pointer and an int is 4 or 8 (depending on ABI), you get sizeof(int *)/sizeof int (4/4=1 for 32-bit machines and 8/4=2 for 64-bit ones) which is 1 or 2.

In C++ when pass an array as an argument to a function, actually you're passing a pointer to an array.

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

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