[英]substitute strlen with sizeof for c-string
我想使用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個字節)。
如果您有一個定義為array的字符數組,則可以使用sizeof:
char text[] = "test";
auto size = sizeof(text); //will return you 5 because it includes the '\0' 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] != '\0' ) 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] ) != '\0' ) i++;
return vOut;
}
0 |
零件對我來說確實過時了,但是我覺得要包含它,不知道為什么...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.