views:

177

answers:

2

Suppose you have a string which is NOT null terminated and you know its exact size, so how can you print that string with printf in C? I recall such method but I can not find out know...

+14  A: 

There is a possibility with printf, it goes like this:

printf("%.*s", stringLength, pointerToString);

No need to copy anything, no need to modify the original string or buffer.

DarkDust
But anyway it's dangerous, somebody will someday printf this string with %s
Pmod
Yes, that's it!
whoi
@Pmod: Not necessarily if the buffer is not exposed to the outside world. It's also very useful to just print *parts* of a string (which may be null terminated, of course). If you really want to see this in action, have a look at the OpenSER/Kamailio SIP proxy where they avoid copying stuff due to this technique a lot (also using sprintf).
DarkDust
I don't have anything against printing a part of NULL-terminated string in a way you described. I also do in that way in my progs. But I am against using NON-NULL-terminated strings to pretend that they're terminated. Someone may some day str(n)cpy it or expose outside without noticing this specific.
Pmod
A: 
#include<string.h> 
int main()
{
/*suppose a string str which is not null terminated and n is its length*/
 int i;
 for(i=0;i<n;i++)
 {
 printf("%c",str[i]);
 }
 return 0;
}

I edited the code,heres another way:

#include<stdio.h>
int main()
{
printf ("%.5s","fahaduddin");/*if 5 is the number of bytes to be printed and fahaduddin is the string.*/

return 0;

}
fahad
Very bad performance due to lots of unnecessary byte reads (which come with a performance penalty if the the byte is not on a word-aligned address on most CPUs) and also the formatting parsing and applying is done for each and every character. Don't do that :-) See my answer for the solution.
DarkDust
Thanks for mentioning
fahad
@DarkDust: only a pathological machine would penalize byte reads not aligned to word boundaries. Are you thinking of word reads not aligned to word boundaries? Or some ancient mips crap or something?
R..
@R..: If you consider x86 brain-damaged and out-dated, I absolutely agree. Because x86 does have a penalty for reading and write non-word aligned memory. So does ARM. See for example [this question](http://stackoverflow.com/questions/3025125/cpu-and-data-alignment) or [this question](http://stackoverflow.com/questions/1855896/memory-alignment-on-modern-processors). The thing is (if I understood that correctly) that data is fetched in word-size chunks from memory and getting the correct byte is another micro-op. No big deal, but in a huge loop it might make a difference.
DarkDust
@DarkDust: you are completely wrong about that for byte reads. Why don't you go do a benchmark? x86 has completely atomic byte operations and always had. It does not fetch word-size chunks (except at the cache level, which fetches much larger chunks and alignment is irrelevant, but I'm talking about already-cached data).
R..