Reputation: 70416
I try to understand this c++ code:
void __fastcall TForm1::Button2Click(TObject *Sender)
{
char temp[50];
sprintf(temp,"%S",Edit1->Text);
Send(temp);
}
void TForm1::Send(char *TX_String)
{
unsigned char checksum = 0x02;
while(*TX_String)
{
checksum ^= *TX_String++;
}
checksum ^= 0x03;
}
My reproduction looks like this:
#include <iostream>
using namespace std;
void prepareAndSend() {
char Command[50];
sprintf(Command,"%s", "65535V");
unsigned char checksum = 0x02;
char* p = Command;
while(*p) {
checksum ^= *p++;
}
checksum ^= 0x03;
std:cout << checksum << std::endl;
}
int main() {
prepareAndSend();
return 0;
}
However I get an error:
error: lvalue required as increment operand checksum ^= *Command++;
This code creates a checksum for text passed from an input field. I am not familiar with c++. Any ideas why it is not working in the fiddle?
Upvotes: 0
Views: 1306
Reputation: 22991
Because char *Command[50];
is not the same as char* TX_String
. char* TX_String
is a pointer to a sequence of characters, while char *Command[50];
is an array of such pointers.
Try this:
void prepareAndSend() {
char Command[50];
sprintf(Command,"%s", "65535V");
unsigned char checksum = 0x02;
char* p = Command;
while(*p) {
checksum ^= *p++;
}
checksum ^= 0x03;
std:cout << checksum << std::endl;
}
Upvotes: 1
Reputation: 4886
In your code which gives you this error, you have:
char *Command[50];
And the error:
error: lvalue required as increment operand checksum ^= *Command++;
basically means that you are trying to increase something which is not a variable.
The point here is that when you have an array like char a[10]
, when you compile the program, it will allocate 10 char
s for you, and the name a
in the assembly code will be replaced with the address of the beginning of the array whenever you use it. Therefore a
itself is not a variable, though can not be increased.
But if you define a char *b = a
, then you are allocating a variable, which has a pointer in it, and can of course be manipulated. Then b++
has a meaning, which is to increase that address.
Upvotes: 1
Reputation: 1563
In original code TX_String is char*
, in your code Command is char**
Instead, make a similar checksum function which accepts char*
, this will make debug easier.
(and replace char* Command[50]
with char Command[50]
)
Upvotes: 0