3 ms·
> 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 thin
by 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.