I'm seeing people using snprintf when I would use memcpy. I even did some testing and it worked with memcpy. Now I was in doubt why use one and not the other. And what is the real meaning of the two.
I'm seeing people using snprintf when I would use memcpy. I even did some testing and it worked with memcpy. Now I was in doubt why use one and not the other. And what is the real meaning of the two.
Both functions have very different purposes and are not equivalent. One is not able to replace the other without an additional implementation.
The purpose of the snprintf()
function is to format strings ending in zero .
The purpose of the memcpy()
function is to copy the content from one memory location to another.
If you use memcpy()
to handle strings, you will need to ensure that the
or NULL
memcpy()
terminator is present at the end of the string since memcpy()
does not guarantee this.
The snprintf()
function is very primitive, whereas string de formatação
has a more elaborate implementation, able to interpret the snprintf()
directives allowing type conversions, numeric bases, etc.
I've seen (horrible) scenarios where the %code% function was used to copy strings:
snprintf( dst, strlen(orig), orig ); /* Não faça isso! */
All this cat can be replaced by just:
strcpy( dest, orig );
That, unbelievable, is equivalent to:
memcpy( dest, orig, strlen(orig) + 1 ); /* Não, não, não! */
Are not you in some kind of horrible scenario out there?
They are not the same thing.
The memcpy function copies n bytes from the memory location pointed to by the first parameter to positions from the address of the second parameter.
The snprintf function writes from the indicated memory location by making the formatting defined in the parameter.