ConfusedBacon
ConfusedBacon

Reputation: 95

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

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

Upvotes: 3

Views: 9937

Answers (4)

Vannes Yang
Vannes Yang

Reputation: 138

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

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

Upvotes: 0

Terry
Terry

Reputation: 338

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.

Upvotes: 0

Bathsheba
Bathsheba

Reputation: 234705

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.

Upvotes: 4

Remy Lebeau
Remy Lebeau

Reputation: 596256

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"; 

Upvotes: 10

Related Questions