K
kooladi
Shouldnt this be const char* ptr="hello";jaysome said:On Tue, 26 Feb 2008 15:19:33 -0500, Kenneth Brody
CBFalconer wrote:
Kenneth Brody wrote:
(e-mail address removed) wrote:
[... size needed for "%p" output ...]
You *cannot* know the size.
<pedant>
Well, you can "know" it at runtime, with snprintf():
7.19.6.5p3
The snprintf function returns the number of characters that
would have been written had n been sufficiently large, not
counting the terminating null character, or a negative value
if an encoding error occurred.
</pedant>
The C standard for fprintf says:
[... returns length or negative for error ...]
and for printf says:
[... returns length or negative for error ...]
which seem to provide an adequate means of determining the size
written. Similarly for sprintf. Amazingly enough, these also
allow detecting i/o errors in the output stream.
But, how big should you make the buffer for sprintf(), as the OP
was using?The C Standard says this about the "%p" conversion specification:"The argument shall be a pointer to void. The value of the pointer is
converted to a sequence of printing characters, in an
implementation-defined manner."This means that this program:#include <stdio.h>
int main(void)
{
printf("%p\n", (void*)0);
return 0;
}can produce the following output in a strictly conforming
implementation:The quick brown fox jumps over the lazy dog.It could also output the text of The Declaration of Independence or of
the book War and Peace. In other words, strictly speaking, the answer
to the OP's question is: we don't know and we can't say.Practically speaking, though, a buffer size that is a generous power
of 2 will work. I'd be comfortable with s[16], but personally I'd use
a very cheap s[32] just for good measure.In my experience, sprintf'ing a pointer value to a string (in, for
example, a debug log message), requires that you use a size for the
string that is sufficient in size by eyeballing it. For example:char s[128];
sprintf("p is %p\n", (void*)p);Although the size 128 is, strictly speaking, not guaranteed to be
sufficient in size to accomodate the "%p" conversion specification
along with the accompanying text, it is sufficient for practical
purposes, all things considered.
I suppose the proper way to do this is:
char *ptr = "hello";