用 sizeof 替换 strlen 代替 C 字符串

substitute strlen with sizeof for c-string

本文关键字:字符串 代替 strlen sizeof 替换      更新时间:2023-10-16

我想使用mbstowcs_s方法但没有iostream标头。因此,我无法使用 strlen 来预测缓冲区的大小。以下方法必须简单地将 c 字符串更改为宽 c 字符串并返回它:

char* changeToWide(char* value)
{
   wchar_t* vOut = new wchar_t[strlen(value)+1];
   mbstowcs_s(NULL,vOut,strlen(val)+1,val,strlen(val));
   return vOut;
}

一旦我把它改成

char* changeToWide(char* value)
{
   wchar_t* vOut = new wchar_t[sizeof(value)];
   mbstowcs_s(NULL,vOut,sizeof(value),val,sizeof(value)-1);
   return vOut;
}

我得到错误的结果(两个数组中的值不同)。解决它的最佳方法是什么?我也愿意接受其他想法,如何在不使用字符串而是纯数组的情况下进行转换

给定一个 char* 或 const char*,你不能使用 sizeof() 来获取由 char* 变量指向的字符串的大小。在这种情况下,sizeof() 将返回指针在内存中使用的字节数(通常在 32 位体系结构中为 4 个字节,在 64 位体系结构中为 8 个字节)。

如果将字符数组定义为数组,则可以使用 sizeof:

char text[] = "test";
auto size = sizeof(text); //will return you 5 because it includes the '' character.

但是如果你有这样的东西:

char text[] = "test";
const char* ptext = text;
auto size2 = sizeof(ptext); //will return you probably 4 or 8 depending on the architecture you are working on.
并不是

说我是这方面的专家,但char要进行wchar_t转换似乎只不过是为完全相同的字节使用更宽的空间,换句话说,在每个char前面加上一些零。

我也不知道C++,只有 C,但我可以通过查看您的代码来推导出它在C++中可能是什么样子,所以这里是:

wchar_t * changeToWide( char* value )
{
    //counts the length of the value-array including the 0
    int i = 0;
    while ( value[i] != '' ) i++;
    //allocates enough much memory
    wchar_t * vOut = new wchar_t[i];
    //assigns values including the 0
    i = 0;
    while ( ( vOut[i] = 0 | value[i] ) != '' ) i++;
    return vOut;
}

0 |部分对我来说真的很过时,但我觉得包括它,真的不知道为什么......