注册 登录
编程论坛 C++教室

对象数组长度的获取问题

sharplong 发布于 2017-05-28 20:19, 2263 次点击
程序代码:
#include <iostream>
#include <string>
using namespace std;

class Student{
public:
    Student(int n,int s){
        number  = n;
        score   = s;
    }
    void print(){
        cout<<number<<"      "<<score;
    }
private:
    int number;
    int score;
};

void cal_size(Student stu[]){
    cout<<"函数内计算的大小"<<sizeof(stu)<<"---"<<sizeof(stu[0])<<endl;
}
int main(){
    Student stu[5] = {
        Student(1,100),
        Student(2,200),
        Student(3,300),
        Student(4,400),
        Student(5,500)
    };
    cal_size(stu);
    cout <<"函数外计算的大小"<<sizeof(stu)<<"---"<<sizeof(stu[0])<<endl;
    system("pause");
    return 0;
}


输出结果为:
函数外计算的大小8---8
函数外计算的大小40---8

期望结果:
函数外计算的大小40---8
函数外计算的大小40---8
问题:
为什么输出结果函数内计算大小不是40--8?是传参的问题吗?我不明白为什么会出现这样的问题。

[此贴子已经被作者于2017-5-28 20:21编辑过]

2 回复
#2
rjsp2017-05-28 22:10
void cal_size(Student stu[])
等同于
void cal_size( Student* stu )
所以你函数内部sizeof的是一个指针。

改成 数组的引用 试试:
void cal_size( Student (&stu)[5] )
#3
sharplong2017-05-28 23:02
回复 2楼 rjsp
用上述方法修改后得到了期望的结果。
开始想到了是sizeof了指针的问题,然而不知道正确形参的写法,。基础有点差。
1