开发者

Printing an array of u_chars

I have an array of u_chars and I want to print it using printf. I don't know the开发者_运维知识库 size of the array:

u_char *ip_p;
printf("%s", ip_p); // EXC_BAD_ACCESS D:<

I want to print this. How can I do this?


That can't be done. A pointer doesn't magically contain information about the size of the data pointed to.

If there's no convention (a terminator byte, or a length encoded somewhere), you can't know how much data is valid, and thus how much to print.


If you don't know the size, how do you expect printf to know? Fix your code to pass the size as an additional argument. Then you can use:

printf("%.*s", size, buf);

However it looks like your data might not be text but binary. If so, I question the value of printing it with printf...


If ip_p is NUL terminated, your code works. Looking the comment in your code fragment I would say it isn't terminated...


If you don't know the size of the data how can you hope to use it? The size must have been available somewhere otherwise how did it get put there!? You must either know the size or have a sentinel value such as a nul character.

If it is not nul terminated, then "%s" is an inappropriate format specifier. Also if the u_char values are not all printable characters, you should not use %s or even %c. You might use %c and substitute non-printing characters with another.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜