3 ms·
What's the standard practice these days in C to move strings with lengths around? I've been out of C for at least a couple of years now, but I can't imagine it'
by andrewmcwatters 5y ago
What's the standard practice these days in C to move strings with lengths around? I've been out of C for at least a couple of years now, but I can't imagine it's changed in that time.
- dragontamer 5y agoI'd assume memcpy. But a more serious answer is to use C++ strings instead, lol. Writing "C-like C++" is probably more beneficial. I do realize that a lot of people prefer to write in pure C (ex: Linux kernel team), but more and more people are realizing the benefits of C-like C++ code.
- andrewmcwatters 5y agoYeah, I would assume as much, too. When I last worked in C, there was no de facto way to do this since so many functions just worked on null termination.
- jstimpfle 5y agoIf you're asking what to do about copying strings, then it's either memcpy(), or rarely str[n]cpy(). strcpy when I can assume the source length is safe but don't know the size of the underlying buffer. strncpy when I want to check the return value and maybe issue an error. For passing references around, I use whatever works. Plain `const char *` argument is certainly a frequent choice for simple name or filepath arguments. That can even mean doing the occasional strlen() when making a copy of that string. It doesn't bother me at all; overall zero-terminated strings are very easy to use. Can't understand why people never stop bitching about it. When the string is not just an opaque ID, but needs to be examined more closely, it's usually more of a "slicey" or a buffer-processing problem - then I'll add an `int len` to the list of arguments, or to the members in a struct. Very rarely I'll create a String class, but usually I don't bother. It feels to me like going against the grain of the language. I don't want to create my own host of string processing functions that take this String as argument, when it's usually simpler to operate directly on the data. Something that I close to never need is the "growable" string class with memory management like std::string. I have no idea right now why I would need such a thing. I tend to write my programs to work on fixed buffers. At most I'll create dynamically sized strings, but a generic string that can grow after creation isn't a frequent use case.
- andrewmcwatters 5y agoI agree with everything you’ve stated. Just curious what others think. Thanks for sharing.