문제

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?

도움이 되었습니까?

해결책

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

다른 팁

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 chars 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.

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])

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top