#strcpy vs sprintf
26 messages · Page 1 of 1 (latest)
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.
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");
Pretty much; I usually try to use strcpy() (or strncpy()) whenever possible, and only sprintf() (or snprintf()) whenever I need formatting
strncpy 💀
when?
tho I prefer strcpy
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
If you have a char array and you always know it's size so you don't need it to be null-terminated
yeah, though when do you want that?
off the top of my head, acpica does this
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
e.g the ACPI spec limits identifiers to 4 chars, so there's no point in accounting for more
True, but I don't see that as much of a problem
I think most uses of strncpy don't actually involve this case, a lot of people use it as a bounded strcpy when that isn't really what it is for
Yea that's fair enough
It's pretty specific
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
lol, yea snprintf would be better for what you're describing
I feel like a lot of things in C are misused like that