如何检索此数组的大小?
How to retrieve the size of this array?
我正在使用 IMidiQueue 到 queue/add IMidiMsg
对象到我的 IMidiQueue mMIDICreated;
有时,我想检索我在上面添加的项目数。我试过这个:
char buffer[50];
sprintf(buffer, "size %d\n", sizeof(mMIDICreated) / sizeof(IMidiMsg));
OutputDebugString(buffer);
但添加 8 项后:
for (int i = 0; i < 4; i++) {
IMidiMsg* one = new IMidiMsg;
// ...
mMIDICreated.Add(one);
IMidiMsg* two = new IMidiMsg;
// ...
mMIDICreated.Add(two);
}
是returns2,不是8。我哪里错了?
假设 mMIDICreated
是一个 指针 ,在指针上做 sizeof
returns 实际指针的大小而不是它的大小指着。另请注意,将数组传递给函数时,它 衰减 指向指向其第一个元素的指针。
如果函数需要数组中元素的数量,您需要将其作为参数传递给函数。
另一种解决方案,也是我推荐使用普通 arrays/pointers 的解决方案,是将 std::array
(for arrays that are known at time of compilation) and std::vector
用于 "run-time" 或动态数组。
看着你的link:
class IMidiQueue
{
...
IMidiMsg* mBuf;
}
存储元素的缓冲区不计入sizeof()
返回的大小。只有指针本身的大小。
不过,还有一个方法int GetSize()
可能对你有用。
sizeof
将 return 对象或类型本身的大小,它是一个常量,在编译时计算,与只能知道的项目数无关在 运行 时间。
你应该使用 IMidiQueue::ToDo
:
Returns the number of MIDI messages in the queue.
我正在使用 IMidiQueue 到 queue/add IMidiMsg
对象到我的 IMidiQueue mMIDICreated;
有时,我想检索我在上面添加的项目数。我试过这个:
char buffer[50];
sprintf(buffer, "size %d\n", sizeof(mMIDICreated) / sizeof(IMidiMsg));
OutputDebugString(buffer);
但添加 8 项后:
for (int i = 0; i < 4; i++) {
IMidiMsg* one = new IMidiMsg;
// ...
mMIDICreated.Add(one);
IMidiMsg* two = new IMidiMsg;
// ...
mMIDICreated.Add(two);
}
是returns2,不是8。我哪里错了?
假设 mMIDICreated
是一个 指针 ,在指针上做 sizeof
returns 实际指针的大小而不是它的大小指着。另请注意,将数组传递给函数时,它 衰减 指向指向其第一个元素的指针。
如果函数需要数组中元素的数量,您需要将其作为参数传递给函数。
另一种解决方案,也是我推荐使用普通 arrays/pointers 的解决方案,是将 std::array
(for arrays that are known at time of compilation) and std::vector
用于 "run-time" 或动态数组。
看着你的link:
class IMidiQueue
{
...
IMidiMsg* mBuf;
}
存储元素的缓冲区不计入sizeof()
返回的大小。只有指针本身的大小。
不过,还有一个方法int GetSize()
可能对你有用。
sizeof
将 return 对象或类型本身的大小,它是一个常量,在编译时计算,与只能知道的项目数无关在 运行 时间。
你应该使用 IMidiQueue::ToDo
:
Returns the number of MIDI messages in the queue.