某些函数具有需要字符串的签名以及该字符串的大小。例如:
WriteConsole(..., "MyString", sizeof(param(1)), ..., ..);
如果我们可以使用字符串文字作为参数并将该文字的大小传递给size参数,那将是非常方便的。例如:
HeatMap
其中param(n)将返回第n个参数。这样就可以省去写一个变量来保存一个不需要的字符串。
是否存在类似的内容,特别是在Visual Studio中?
答案 0 :(得分:3)
不,Visual Studio中不存在这样的内容。它可能是这样做的,所以你可以发送部分字符串,例如:
WriteConsoleW(hConOut, L"Hello" + 2, 2, ...);
会写" ll"到与hConOut
句柄关联的控制台。
您可以通过编写类似:
的内容为字符串文字创建自己的类函数宏/* Needed for _countof macro in MSVC. */
#ifdef __cplusplus
#include <cstdlib>
#else
#include <stdlib.h>
#endif
/* Use _countof(array) where possible, else use
* sizeof(array) / sizeof(array[0])
* for the number of units in the string literal.
*/
#ifdef _countof
#define WriteConString(hConOut, str, pdwWritten) \
WriteConsole(hConOut, \
(str), \
_countof(str), \
(pdwWritten), \
NULL)
#else
#define WriteConString(hConOut, str, pdwWritten) \
WriteConsole(hConOut, \
(str), \
sizeof(str) / sizeof(*(str)), \
(pdwWritten), \
NULL)
#endif
如果您不关心C ++或the _countof
macro,则可以将代码缩短为仅包含最后一个#define
。
但是,这仅适用于字符串文字和静态数组的字符。 malloc
,HeapAlloc
等所有返回指针,因此_countof(my_array_of_32767_elts_as_ptr)
(和可比较的sizeof(array)/sizeof(array[0])
表达式)将导致非常小的数字,而不是阵列。指针不会编码数组中元素的数量。
答案 1 :(得分:-1)
我不明白你的问题。
C样式字符串以null结尾,因此您调用的函数可以通过搜索字符串中的第一个空字符轻松找到字符串的结尾。
例如strcmp之类的函数不需要长度。
如果你在谈论没有终止标识符的数组,那么通常函数将是类型:
int func1(const T* data, size_t length);
或类似。