Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

passing address to sprintf()

Status
Not open for further replies.

randomprocess

Programmer
Sep 30, 2011
2
US
How do I do this guys....

char *buff2 = " "; // is malloc'd in real code.
sprintf(&buff2[2],"xx"); // is sprintf(&buff2[2],"%02X",*ptr) in real code.
printf("%s\n");

obviously trying to write "xx" to &buff2+2 and &buff2+3.
 
Well you should sprintf to a temporary buffer first, then use memcpy() to move two chars to your destination buffer.

sprintf would always append a \0 to whatever it did, so if buff2[4] was really important to you, it would be trashed.

But as far as general syntax goes, it's a valid thing to do.


--
If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
 
That was my impression (that it was valid). Problem is that it accesses the data rather than the address of the data. &buff2[2] and buff[2] are equivalent... and I did not think they should be... I very much did not think they should be... bug in the compiler?

Thanks for the post.
 
I think you would need to post some real code, because there are too many mistakes in the paraphrased code to be really sure.

I mean, when you start saying things like "&buff2+2 and &buff2+3", then you're way off base if your intent is to try and write characters to some position in a string that buff2 points to.

&buff2+2 is valid syntax, it's just that it means something completely different. You can't just go by "well it compiles".



--
If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top