How To Get Rid of Null Terminator In Pointer For WriteFile Function

Hello and thank you!
I am attempting to send the character 'a' to a microcontroller. Although I am sending the character a, there is also another character being sent and I am 95% sure it is '\0' because that is what my microcontroller is printing out.

Here is the code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
bool Port::writePort(char *toWrite)
{
	if(WriteFile(hSerial, toWrite, sizeof(toWrite), &bytesRead, NULL)){
		cout << "Write Successful\n";
		return true;
	}else{
		cout << "Write failed";
		return false;
	}
}

int main(int argc, char *argv[])
{
	Port myPort;

	char *toSend = argv[1];

	myPort.writePort(toSend);

    return 0;
}


Side question, how can I run/debug my code from the IDE and give main initial parameters?

Edit: I've been doing it so far via cmd
Last edited on
sizeof(toWrite) is the size of the pointer, not the length of the string.
You want to use strlen(toWrite)
I am attempting to send the character 'a' to a microcontroller.

If you're just trying to send a single char to your port (the first char in your string?) then you need:

1
2
3
// Writes just the first byte of the string (assumed to be
// chars -- and sizeof(char) == 1)
WriteFile(hSerial, toWrite, 1, &bytesWritten, NULL))


or you can enforce the use of chars

1
2
// toWrite now a char, not a char*
writeFile(hSerial, &toWrite, 1, &bytesWritten, NULL);


with

char toSend = argv[1][0];

But if you do want to write the whole string (while comes from a command line?), it is probably best to include the null terminator, which requires strlen(toWrite) + 1.

how can I run/debug my code from the IDE

That depends on which IDE you mean.

For Visual Studio, see your project's properties. On the "Debugging" tab, there's a chance to define the "Command Arguments".

Andy
Last edited on
Aha, thank you very much, both of you!
And thanks Andy, for the MSVS help.
Topic archived. No new replies allowed.