'Initializing': Cannot convert from 'const wchar_t[35]' to 'LPWSTR'

7.9k Views Asked by At

i am currently learning C++ and want to change my desktop wallpaper. However i am getting this error above.

#include <string>
#include <iostream>
#include <Windows.h>

using namespace std; 

int main() {

LPWSTR test = L"C:\\Users\\user\\Pictures\\minion.png";

int result = SystemParametersInfo(SPI_SETDESKWALLPAPER, 0, 
test, SPIF_UPDATEINIFILE);


}

A value of type "Const wchar_t*" cannot be used to initialize an entity of type LPWSTR

Any ideas?

Thanks

4

There are 4 best solutions below

5
On BEST ANSWER

LPWSTR is an alias for wchar_t*, ie a pointer to a non-const character.

A string literal is a const array of characters, in your case a const wchar_t[35]. It decays into a pointer to a const character, pointing at the 1st character in the literal.

You can't assign a pointer-to-const to a pointer-to-non-const. That would allow writing access to read-only memory.

Use LPCWSTR instead, which is an alias for const wchar_t*.

LPCWSTR test = L"C:\\Users\\user\\Pictures\\minion.png"; 
0
On

Another way to resolve this compilation error is to set Conformance Mode to Default in the project Properties -> C/C++ -> Language. At least it worked in my VS2019 project.

2
On

Try this, I'm sure this can be compiled.

LPCWSTR dd = L"C:\\Users\\user\\Pictures\\minion.png";
si.lpDesktop = reinterpret_cast<LPWSTR>(&dd);
0
On

The MSVC compiler is getting less and less permissive. On the whole that's a good thing.

L"C:\\Users\\user\\Pictures\\minion.png" is a literal of type const wchar_t[34] (the extra element is for the string terminator). That decays to a const wchar_t* pointer in certain circumstances.

LPWSTR is not a const pointer type so compilation will fail on a standard C++ compiler.

The solution is to use the const pointer type LPCWSTR.