简体   繁体   中英

Variable going out of scope between classes in C++

I am just getting back into programming, so forgive me if this is very silly.

I have 2 classes (for now). One is the Windows Form class, where I am using a Button_Click event to trigger a communication port opening. I want to pass data that the user entered on the form on to the Communication class for further processing (sending). This is the part that initializes and calls the Communication class:

wchar_t * data = new wchar_t[nLength];
    *data = *wch;

    SerialCommunication comm1;
    bool comm1ok = comm1.SerialWrite(data);

Variable "data" is a pointer, so I want to pass its address to the other class to use. This is my 2nd class:

bool SerialCommunication::SerialWrite(wchar_t * datar){...

But the data never makes it there. It goes out of scope as soon as the SerialWrite() function starts up. Do I need to declare this pointer in some other way to make sure it doesn't disappear when I move between classes?

The classes are both public, as far as I know (well, I wrote the SerialCommunication one, so I know it's public).

What am I doing wrong? What should I change?

Thanks!

This:

*data = *wch;

does not do what you think (or what I assume you think). It just copies the first element of wch into the first element of data .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM