Good evening!

I can not display the string LPTSTR ... Here is the code:

char *buffer[UNLEN + 1]; // буфер DWORD size; // размер size = sizeof(buffer); // размер буфера if (GetUserName((LPWSTR) buffer, &size) == 0) printf("Error GetUserName"); // при ошибке функция вернет 0 printf("%s", buffer); getch(); return 0; 

Only the 1st letter is displayed ... What is the error? And what function can display the range of available memory addresses?

Thank!

  • Do not write more than one question mark. - Nicolas Chabanovsky
  • What is an "accessible memory address"? (And why do you need it?) Here is the current stack frame - is it available? And the allocated heap bytes? And unselected? - VladD
  • I myself am wondering, the task in the lab is ... Maybe it is operative memory. - Alerr
  • HashCode, OK. - Alerr
  • @Alerr: well, we're all guessing too. - VladD


2 answers 2

Uh ... Well, you give! (LPWSTR)buffer - this is not allowed. Hard C-shnyy caste.

Try this:

  1. WCHAR buffer[UNLEN+1]
  2. size = UNLEN + 1;
  3. wprintf(L"%s",buffer)

The fact is that LPWSTR is a pointer to a string of long characters. You brought a string from the ordinary, and the function GetUserName lied that it is from long. Lying is not good. The function has written into your memory area (possibly with overflow, because the size is yours in short characters!) Long characters, and now the printf function, of course, cannot output anything.

  • Swears at% s - Alerr
  • @Alerr: well, yes, corrected. I had to L - VladD
  • And why, when attributing L, it ceases to curse, I notice this “L” in the programs several times already. - Alerr
  • @Alerr: because without L is a string of short, single-byte characters. And with L is a double byte string. wprintf wants just that. - VladD
  • four
    GetUserName translated into 2 signatures: GetUserNameA( LPCSTR ...) and GetUserNameW( LPCWSTR ... ) . Therefore, it is incorrect to WCHAR pointer to WCHAR , in principle! If you already use WCHAR , then use the appropriate function. And for the ANSI version of the @ Alerr code, it was enough just to change GetUserName to GetUserNameA . - mega

And if you try this

 (GetUserName((LPWSTR)buffer,&sizeof(buffer))==0) 
  • swears at sizeof - Alerr
  • 2
    it is clear, where does the sizeof(...) address come from? - VladD