回 帖 发 新 帖 刷新版面

主题:[讨论]大家来看看一个简短的程序,求原因

在写程序的时候碰到了点问题, 然后我就写了下面的实验代码, 输出结果是:
The number of elements of the array is :10
The number of elements of the array is :1
请按任意键继续. . .

同一个数组, 我只不过是放到不同的函数里处理, 为什么会有不同的结果?

#include <iostream>
using namespace std;

void CheckSize(int Array[])
{
    cout<<"The number of elements of the array is :"<<sizeof Array / sizeof Array[0]<<endl;
}

void main()
{
    const int size = 10;
    int Array[10];
    cout<<"The number of elements of the array is :"<< sizeof Array / sizeof Array[0]<<endl;
    CheckSize(Array);
}

回复列表 (共4个回复)

沙发

#include <iostream>
using namespace std;

/*
void CheckSize(int* pArray)
{
    cout<<"The number of elements of the array is :"<<sizeof pArray / sizeof pArray[0]<<endl;
}
*/
const int size = 10;
typedef int ARRAY[size];

void CheckSize(ARRAY& ar)
{
    cout<<"The number of elements of the array is :"<<sizeof ar / sizeof ar[0]<<endl;
}


int main()
{
    // const int size = 10;
    // int Array[size];
    ARRAY ar;
    // cout<<"The number of elements of the array is :"<< sizeof Array / sizeof Array[0]<<endl;
    cout<<"The number of elements of the array is :"<< sizeof ar / sizeof ar[0]<<endl;
    CheckSize(ar);
}


CheckSize(int Array[])等价CheckSize(int*),是指针。 所以sizeof Array,结果是4个字节。而sizeof Array[0]也是4个字节,所以,/后,结果为1.得不到长度。 正确的在上面。

板凳

void CheckSize(int Array[10])
{
    cout<<"The number of elements of the array is :"<<sizeof Array / sizeof Array[0]<<endl;
}

如果我把子函数改成这样, 运行结果却还是和原来的一样...这也是指针么?...我囧了...

3 楼

你改不改都一样。指定不指定10,编译器都忽略掉。结果就是int* Array 。所以,sizeof Array,得不到总的长度。就是一个指针的长度4字节。

4 楼

你写的第一个void CheckSize(int Array[])
该数组作为参数时,自动退化成同类型的指针
而sizeof(* p) = 4
所以结果还是1

我来回复

您尚未登录,请登录后再回复。点此登录或注册