#strcpy vs sprintf

26 messages · Page 1 of 1 (latest)

ripe badge
#

lets say I have an empty char array. I noticed that strcpy and sprintf kinda does the same thing but strcpy doesnt have formatting? is that the only difference?

misty oxideBOT
#

When your question is answered use !solved to mark the question as resolved.

Remember to ask specific questions, provide necessary details, and reduce your question to its simplest form. For tips on how to ask a good question use !howto ask.

wise acorn
#

The difference is in the way you use it

#

with srtcpy you copy the string from one char array to a another empty char array so it would look like

#
// source
char src[] = "This is a string"

// destination
char des[100];

// copying the strings using strcpy
strcpy(des, src); // now des contains the string "This is a string"
#

while with sprintf it is direct if you know what I mean wait let me show you it is better if I do

#
// destination
char des[100];

sprintf(des, "This is a string");

vocal tree
torn tide
#

strncpy 💀

wise acorn
#

it is actually useful sometimes

torn tide
#

when?

wise acorn
#

tho I prefer strcpy

wise acorn
# torn tide when?

i cant remember of a scenario must have been a decade since I last used it I mostly use strcpy

#

if I need to do some like that

sinful tundra
# torn tide when?

If you have a char array and you always know it's size so you don't need it to be null-terminated

torn tide
sinful tundra
#

off the top of my head, acpica does this

torn tide
#

also here is something to consider: strncpy always writes n bytes, e.g. if there is 10 extra bytes of capacity it will write 10 null terminators

sinful tundra
sinful tundra
torn tide
sinful tundra
#

Yea that's fair enough
It's pretty specific

torn tide
#

I've seen several examples of where people manually write a null terminator after the strncpy because they realize that issue exists, but don't realize that strncpy isn't made for what they're doing

#

snprintf actually works as a better bounded strcpy thinking about it lol

sinful tundra
#

lol, yea snprintf would be better for what you're describing
I feel like a lot of things in C are misused like that