PDA

View Full Version : how to limit char * arrays?



mhoover
24th June 2009, 03:11
I noticed both the QUdpSocket::readDatagram() and QUdpSocket::writeDatagram() functions accept char *'s as parameters.

On the readDatagram side you're supposed to pass in a length parameter, where I've been putting a constant: 1024.

But when I send char *'s and then receive them, I get these trailing characters. For example when I send: "CONTAIN_STRANGEMATERIALFACILITY"

I get: "CONTAIN_STRANGEMATERIALFACILITY¿äî"

I've tried making the last character '0' and NULL, and newline (10), but they don't work.

My server code:

QHostAddress the_address;
quint16 the_port = 0;
char char_incoming[1024];

readDatagram( (char *)char_incoming, 1024, &the_address, &the_port );
cout << "incoming string is: " << char_incoming << endl;

And my client code:

QString request_string( "CONTAIN_STRANGEMATERIALFACILITY" );
char buffer[512];
int buffer_length = snprintf( buffer, sizeof buffer, request_string.toAscii().data() );
cout << "buffer_length = " << buffer_length << endl;

//buffer[ buffer_length ] = 10; // tried this as well, just puts in a newline
//buffer_length++;

int success = writeDatagram( buffer, host_address, port_number );

And then on the server side I get a bunch of junk.

I'm not sure how I can know the size before I read it.

wysota
24th June 2009, 08:39
readDatagram() returns the number of bytes actually read.

mhoover
24th June 2009, 19:38
Ah. I should have thought of that.

Thanks again, wysota.