2 ms·
> OK... where? In the automatic storage, duh, where everybody else puts them today. > But not everyone wants their string metadata in the heap. Exactly, so y
by Joker_vD 3y ago
> OK... where?
In the automatic storage, duh, where everybody else puts them today.
> But not everyone wants their string metadata in the heap.
Exactly, so you don't put them there, which is what I am proposing: instead of putting the string length before, or the null delimiter after, the string itself, you put it near the pointer that points to the beginning of the (sub)string.
- ajross 3y ago> you put it near the pointer that points to the beginning of the (sub)string. And now you have a "string pointer" which is distinct from a "data pointer". You can't allocate a heap block and "put a string in it" because the special thing at the start needs to go with the pointer and not the data in the block. And your 1970's compiler on your PDP-11 with 48kb of RAM needs to manage that. Good luck to you. Again, we're not answering the question "Can a better string implementation than C be designed?". Clearly the answer is yes. Go pick your favorite, there are literally dozens. We're asking "What else should Richie have done with C that would have been better?". And... it's not what you're suggesting for sure.
- Joker_vD 3y ago> And now you have a "string pointer" which is distinct from a "data pointer". You can't allocate a heap block and "put a string in it" because the special thing at the start needs to go with the pointer and not the data in the block. The second sentence doesn't follow from the first one. struct string { char (*ptr)[static len]; size_t len; }; struct string new_copy = { .ptr = malloc(100), .len = 100; }; new_copy = strcpy(new_copy, "some other string"); // string literal is a syntactic sugar for statically allocated 'struct string' with 'ptr' set to an unnamed, statically allocated char[] buffer inside it, and proper 'len' field. struct string strcpy(struct string dest, struct string src) { struct string result = { .ptr = dest.ptr, .len = min(dest.len, src.len) }; memcpy(result.ptr, src.ptr, result.len); return result; } Or you can do struct string *new_copy = malloc(100 + sizeof(struct string)); new_copy->ptr = (char*)(new_copy + 1); new_copy->len = 100; if you really want to. Just don't pass naked "char*" around, that thing has no obvious extent.
- ajross 3y agoThat's C, though. You're writing C. DMR gave you that, in 1972. (Actually not, because you had to wait for structs, but you know what I mean). But what you seem to be asking for is support in the language for strings that work like this. And that causes problems because of that special handle you've invented. Now strings aren't arrays anymore, they can't have pointers taken to them, they can't have substrings in a natural way, they can't live in ordinary POD memory as a unified thing. All of which is totally solvable in the runtime of a language written in 2003 or whenenver. But not on a PDP-11.