运算符返回冲突的大小
Size of operator return conflict
这里有一些代码
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);
相关文章:
- 来自 std::list 的迭代器 .end() 按预期返回"0xcdcdcdcdcdcdcdcd"但 .begin()
- 什么时候在C++中返回常量引用是个好主意
- 从嵌套循环中的 std::list 中删除将返回访问冲突
- 访问冲突投射到无效*并返回
- 为什么我的布尔函数返回 true 会导致读取访问冲突?
- 从C#返回调用C++dll函数的值时发生访问冲突
- 基类的返回类型与使用 auto 的派生类冲突
- c++抛出0xC0000005:写入位置0xFEEEFEEE的访问冲突.从main返回时
- 返回指针会扰乱对象(访问冲突)
- 为"虚拟无效"指定的冲突返回类型
- c++返回元素在没有代码的行上给出访问冲突
- 当函数在fread()应用于局部结构变量后返回时发生访问冲突
- 运算符返回冲突的大小
- c++中返回类型名称与方法名称冲突
- 错误:指定的返回类型冲突,与通常不同
- Bcp_init返回访问冲突
- c++ Vector读访问冲突Mylast返回0x8
- c++复制构造函数和返回临时对象的冲突
- 返回stbi_load函数的结果并将其用于glTexImage2D会导致内存冲突
- 尝试返回同一类中的私有变量时C++ "Getter"方法抛出访问冲突