运算符返回冲突的大小

Size of operator return conflict

本文关键字:冲突 返回 运算符      更新时间:2023-10-16

这里有一些代码

class DengkleTryingToSleep{
public:
int minDucks(int ducks[]);
int temp(int ducks[]){
int size=sizeof(ducks);
cout<<"sizeof="<<size<<"n";
}
};

int main (int argc, const char * argv[])
{
DengkleTryingToSleep dt;
int arr[]={9,3,6,4};
cout<<"sizeof "<<sizeof(arr);
cout<<"nsizeof from function "<<dt.temp(arr);
return 0; 
}

它的输出是

sizeof 16
sizeof from function sizeof=8

我不知道它是如何工作的,因为它返回16(正如在main内部调用时所预期的那样)当从函数调用时返回8

因为数组在传递给函数时会衰减为指针。您在temp函数中得到了一个指针的大小。

如果你需要知道函数中数组的长度。。。你也必须把它传进来。

实际上这个函数:

int temp(int ducks[])

与此功能完全等效:

int temp(int *ducks)

没有任何区别。没有区别。因此,无论您传递什么,无论是数组还是指针,它都将成为函数中的指针。

这意味着,当你在函数中写入sizeof(ducks)时,它完全等同于sizeof(int*),它在你的机器上返回8(我猜,你的机器有64位操作系统,指针的大小是8字节)。

如果你想传递一个数组,并且它不会衰减为指针类型,那么就这样做:

template<size_t N>
int temp(int (&ducks)[N])
{
    int size=sizeof(ducks);
    cout<<"sizeof="<<size<<"n";
}

现在它将打印16。请注意,函数N内部表示数组中项目的计数。因此,在您的情况下,它将是4,因为数组中有4元素。这意味着,如果你需要数组的长度,你不需要将其计算为sizeof(bucks)/sizeof(int),因为你已经知道数组的长度是N

还要注意,这种方法有一个限制:现在您不能通过动态分配的数组:

int *a = new int[10];
dt.temp(a); //compilation error
//but you can pass any statically declared array
int b[100], c[200];
dt.temp(b); //ok - N becomes 100
dt.temp(c); //ok - N becomes 200

但是在C++中,您有一个更好的选择:使用std::vector<int>

int temp(std::vector<int> & ducks)
{
     std::cout << ducks.size() << std::endl;
}
//call it as
std::vector<int> v = {1,2,3,4,5,6}; //C++11 only, or else : use .push_back()
dt.temp(v);