43

Please, how can I find out the length of a variable of type wchar_t* in c++?

code example below:

wchar_t* dimObjPrefix = L"retro_";

I would like to find out how many characters dimObjPrefix contains

MSalters
  • 173,980
  • 10
  • 155
  • 350
Jacob
  • 1,242
  • 2
  • 9
  • 14
  • Do you mean a single character or a string? – Mark Byers May 17 '10 at 23:25
  • 2
    Sorry, I should have made that clearer. I wanted the number of characters. wcslen seems to do what I want according to http://msdn.microsoft.com/en-us/library/78zh94ax(VS.71).aspx Thanks tusbar. – Jacob May 17 '10 at 23:39
  • 1
    @Jacob: a `wchar_t` is not a string, and it doesn't have a length. I assume you're asking about `wchar_t*`. Those asterisks aren't just for show, you know. They can't be left out without changing the meaning of the code (and the question) – jalf May 18 '10 at 02:29
  • @jalf thanks and sorry. I have edited the question to include a code sample of what I was trying to find, with asterisks included. – Jacob May 18 '10 at 02:38
  • Edited question to show proper `L""` syntax for wide strings. – MSalters May 18 '10 at 12:44
  • 1
    So you want the length of the block of memory that a `wchar_t*` points to. – Lightness Races in Orbit Mar 31 '11 at 14:14
  • @Tomalak, no. From the question - "I would like to find out how many characters dimObjePrefix contains". Number of characters, not length of the block of memory. Plus this question has been marked as answered for almost a year. – Jacob Mar 31 '11 at 22:32
  • @Jacob: You're right; I guess I was generalising. I meant to talk about a function of the length of the block of memory that the `wchar_t*` points to, with a focus on that the size of the pointer is irrelevant, and that the pointer itself contains no characters. Meanwhile, I wasn't aware that there was a time limit on contributing to SO questions; can you point me to that entry in the FAQ? – Lightness Races in Orbit Mar 31 '11 at 23:08

2 Answers2

51

If you want to know the size of a wchar_t string (wchar_t *), you want to use wcslen(3):

size_t wcslen (const wchar_t *ws);
jameshfisher
  • 34,029
  • 31
  • 121
  • 167
Bertrand Marron
  • 21,501
  • 8
  • 58
  • 94
12

Assuming that you want to get the length of null terminated C style string, you have two options:

  1. #include <cwchar> and use std::wcslen (dimObjPrefix);,
  2. or #include <string> and use std::char_traits<wchar_t>::length (dimObjPrefix);.
wilx
  • 17,697
  • 6
  • 59
  • 114