1

my problem is that when I use this:

LPSTR a = "0";
LPSTR b = "1";
LPSTR c = "2";
LPSTR d = "3";
LPSTR e = "4";

TCHAR strex[5];
DWORD x;

myFile = CreateFile("C:\\a.txt", FILE_WRITE_DATA, NULL, NULL, CREATE_ALWAYS,
FILE_ATTRIBUTE_NORMAL, NULL);

TCHAR n[5];
StringCchCopy(n, 5, a);
StringCchCat(n, 5, b);
StringCchCat(n, 5, c);
StringCchCat(n, 5, d);
StringCchCat(n, 5, e);

strex = n;

WriteFile(myFile, strex, (DWORD)(sizeof(strex)), &x, NULL);
CloseHandle(myFile);

I get this error for this line: strex = n; error C2106: '=' : left operand must be l-value

If I change TCHAR strex[5]; to TCHAR strex; then I get the following errors:

error C2440: '=' : cannot convert from 'TCHAR [5]' to 'TCHAR'

and

error C2664: 'WriteFile' : cannot convert parameter 2 from 'TCHAR' to 'LPCVOID'

Is there anyway to accomplish what I'm trying to do with different code? Help would be appreciated.

Dav3
  • 19
  • 4
  • 3
    Arrays are not lvalues in C++. Thus, the statement `strx = n;` makes no sense whatsoever, and the compiler rightly complains about it. Changing `strex[5]` to simply `strex` should, at a very minimum, flag warnings and or errors everywhere in this code, and *all* of them should be heeded. Learning C++ by guesswork isn't productive. [I suggest a good book](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list) – WhozCraig Jul 21 '17 at 23:14
  • 1
    Arrays are second class citizens in the C and C++ languages, and can't be assigned as `strex = n;`. You have to copy each element individually. In C++ you have `std::string` which *can* be assigned. – Bo Persson Jul 21 '17 at 23:17
  • Thanks for the help WhozCraig and Bo Persson. – Dav3 Jul 21 '17 at 23:20

1 Answers1

0

You must be using an old compiler as C2106 is the wrong error. It should be

error C3863: array type 'TCHAR [5]' is not assignable

When you:

TCHAR strex[5];

You are creating an array of five chars on the stack. strex is a pointer to that array. You can not change that pointer. So when you:

strex = n;

You are asking to assign the pointer n to the pointer strex. If you want a pointer to n then:

TCHAR* strex= n;

Will work. But you don't even have to do that, you already have the pointer with n!

WriteFile(myFile, n, (DWORD)(sizeof(n)), &x, NULL);

lakeweb
  • 1,859
  • 2
  • 16
  • 21
  • Thank you, you're correct, I tried what you said and it worked. I need to learn more. – Dav3 Jul 21 '17 at 23:28