用宏找出C中数组的大小
我很难理解这个宏是否做了它应该做的事情。它位于我正在包装的第三方 dll 中。
#ifdef __cplusplus
#define NULL 0
#else
#define NULL ((void *)0)
#endif
#define GTO_ARG_SIZE(arg) (long)((arg)==NULL ? 0 : (long)(arg)[0])
它应该给出 arg 的长度,其中 arg 在我的例子中是一个 long*。它只是指向一个 long,但当 arg 是一个 long 数组时,也会使用宏...
根据我的理解,如果指针不为 NULL,它会返回 arg[0] 处的值。但是当 arg 指向 long 时,它返回 long 的值,而不是 arg (1) 的大小...
已解决:
就像你们中的许多人所说,神话结构将其大小作为第一个元素。抱歉,我没有关于 dll 的文档,所以我只是在深入研究代码后才发现的。一开始我想知道我是否真的对 C/C++ 知之甚少。 谢谢大家
I have trouble understanding if this macro does what it should. It is in a third party dll I am wrapping.
#ifdef __cplusplus
#define NULL 0
#else
#define NULL ((void *)0)
#endif
#define GTO_ARG_SIZE(arg) (long)((arg)==NULL ? 0 : (long)(arg)[0])
It is supposed to give the length of arg where arg is in my case a long*. It just points to a long but the Macro is also used when arg is an array of longs...
From my understanding it returns the value at arg[0] if the pointer isn't NULL. But for when arg points to a long, it returns the value of the long, not the size of arg (1)...
RESOLVED:
Like many of you said, the mythical structure contains it's size as the first element. Sorry I have no documentation on the dll so I figured out only after digging a bit into the code. I was wondering at first if I really knew so little about C/C++.
Thanks all
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
也许第三方 DLL 假设数组是这样表示的,第一个元素包含长度?如果数组也是从 1 开始并且进行边界检查的话,那就有点道理了。
当您不提供有关代码的更多详细信息时,很难更具体。
计算数组长度的更经典的宏是:
请注意,这仅适用于实际数组,其中数组声明在范围内。特别是,这在 C 中不起作用:
上面不会打印
4711
;数组的大小不是数组在函数调用中衰减为的 const int * 类型的一部分。通常不可能在 C 中执行此操作,即查找已传递给接受指针的函数的数组的大小。Maybe the third-party DLL assumes that arrays are represented like that, with the first element containing the length? That would make kind of sense, if the arrays are also 1-based and bounds-checked.
Hard to be more specific when you're not giving more details about the code.
A more classical macro to compute the length of an array is:
Do note that this only works for actual arrays, where the array declaration is in scope. This, in particular, does not work in C:
The above will not print
4711
; the array's size is not part of theconst int *
type that the array decays to in the function call. It's not in general possible to do this in C, i.e. find the size of an array that has been passed to a function accepting a pointer.这只是返回 arg 指向的 long,如果指针为空,则返回零。
我可以看到返回 arg 长度的唯一方法是,如果 arg 是指向结构(或结构的长成员)的指针,它恰好代表了它所使用的结构的长度,虽然看起来像是一个远景。
编辑——这个神秘的结构更有可能是一个带有边界信息的数组,正如 unwind 所说的那样。
This simply returns the long pointed to by arg, or zero if the pointer is null.
The only way I can see this returning the length of arg, is if arg is a pointer to a struct (or a long member of a struct) which happens to represent the length of the structure it's used in, seems like a long shot though.
Edit — this mythical structure is more likely to be an array with bounds information as unwind says than anything else.