Can you cast an array of char to a char*? Thanks.

Nemo

Its not necessary because the array can be treated either way in most cases. Post an example of what you are not sure about.

If you have to ask about casting, there's a 99% chance that it's the wrong thing to do.

Yeah, I know to avoid casting but I dont see another way.

To Ancient: say i have "this is a test" stored in an array, is there a way to turn that into a char* for function returing purposes. Thanks.

A code example would be much preferred.

[LIST=1]
			do
			{
				if(ReadFile(myReadCom, &myReadByte, 1, &bytesRead, NULL))
				{
					//strncat_s(myIncomingMessage, sizeof(myIncomingMessage), (const char*)myReadByte, 1);
					//cout << "Byte Read. Process it." << endl;
					incomingMessage.myIncomingMessage[index] = myReadByte;
					index++;
				}
				else
					cout << "Read message error." << endl;
			}
			while(bytesRead);
			
			incomingMessage.myIncomingMessage[index-1] = NULL;
			myIncomingMessage = reinterpret_cast<char*>(incomingMessage.myIncomingMessage);[/LIST]

This is the part I need help with. The entire module compiles and when I step through it works until I cout the message. Its jibberish. Thanks.

What is incomingMessage.myIncomingMessage, an array of char?
What is myIncomingMessage?

incomingMessage.myIncomingMessage[index-1] = NULL;

Don't use NULL where you mean '\0' -- and aren't you putting it in the wrong place?

>>myIncomingMessage = reinterpret_cast<char*>
you can not return a character array from a function when it has been declared on the stack . The below is wrong because the array will disappear when the function returns, and typcasting will not help that.

char* foo()
{
    char myIncomingMessage[255];

    return myIncomingMessage; // <<<< WRONG
}

There are a couple work-arounds.

1) declare the array as static

char* foo()
{
    [b]static[/b] char myIncomingMessage[255];

    return myIncomingMessage; // <<<< OK
}

or dynamically allocate the array

char* foo()
{
    char *myIncomingMessage = new char[255];

    return myIncomingMessage; // <<<< OK
}
commented: Replied timely, and solved my problem +1

I appreciate it guys. Ill work on it some more and post if I have anymore questions. Thanks.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.