Best Way to Assign Value to constant char (and other things)?

Hello and thank you! I'm a bit new so bear with me.
I'm attempting to conduct serial communication between my computer and an Arduino.
I'm using the CreateFile(...) function to attempt to do this.
Coming from the world of java, I just get a bad itch when something that should be an instance variable isn't.
My problem is that one of the variables, the file name, is of type LPCSTR, which, as I understand it is a long pointer (16bit) constant character.
It is equivalent to: const char*

Now I have two questions: Here is part of my code for reference:

1
2
3
4
5
6
7
8
9
10
class Port{
public:
    Port(string str);
private:
    LPCSTR portName;
};

Port::Port(string str){
    portName = str;
}


The first issue is that I cannot assign a string to a constant character. I cannot assign a string to a character PERIOD. That is obvious, but then how am I suppose to put the value of lets say "COM3" in there?
Secondly, even if the conversion did work, the value is declared constant. So I anticipate that as the second error. I cannot give this constant a value after I initialize it.

I'm using the createFile(...) function as per this link:http://www.codeproject.com/Articles/3061/Creating-a-Serial-communication-on-Win32#creating

EDIT: When I do this:

portName = "COM3";

It works. Why can string literals go into things of type char??
Last edited on
A string in quotes is of type const char*.
Use c_str() method of std::string class you are using.

Also, as you correctly say, you cannot assign to a const char*, use a char* instead (or LPSTR if you prefer, is the same thing).

A pointer is not '16 bit' and there is no more 'long pointers' in modern versions of windows, all of them are 32 or 64 bit.
You should NOT assign a std::string's internal char* to another char*, because it will be deleted as soon as its scope goes out.
(In your case, as soon as your Port::Port function ends, your LPCSTR pointer will be pointing at invalid memory)

You should really use another std::string to store a std::string, or do your new/delete allocations yourself (which is what std::string does).

Greetings modoran for successfully reaching and passing 1337 posts.
Last edited on
Topic archived. No new replies allowed.