3 ms·
Off the top of my head (in D syntax): char[3] s = "abc"; char* p = cast(char*)malloc(s.length + 4); assert(p != null); char[] a = p[0 .. s.leng
by WalterBright 8y ago
Off the top of my head (in D syntax):
char[3] s = "abc";
char* p = cast(char*)malloc(s.length + 4);
assert(p != null);
char[] a = p[0 .. s.length + 4];
a[0 .. 3] = s[];
a[3 .. 3+4] = "1234";
It's more verbose than necessary, but I wanted to illustrate the idea. Note how the allocation is turned into a dynamic array.
Note that my proposal is not for a new memory allocation scheme for C, just a way to map data onto arrays.
- drfuchs 8y agoYou don't seem to understand heap vs. stack. The call to malloc() does a heap allocation, and the question was "without using the heap in any way". If it makes it conceptually easier, how about a solution where the string is simply a global variable? No malloc allowed.
- vkazanov 8y agoYou don't seem to understand who you are arguing with :-)
- WalterBright 8y agoI showed you how to do that in another reply.
- geezerjay 8y ago> You don't seem to understand heap vs. stack. Please check who you are replying to. https://en.wikipedia.org/wiki/Walter_Bright https://en.wikipedia.org/wiki/Walter_Bright
- deleted 8y ago[deleted]
- jkabrg 8y agoWalterBright posted the following code snippet somewhere above: char foo[9]; foo[] = "abc"; foo[3..3+5] = "1234"; `foo` is an array. `foo[3..8]` is a slice, which is an object that does its own bounds-checking. I don't think the heap is used here. Another explicit example: char foo[5] = "abcd"; // still NUL-terminated, carries length aswell char[] bar = foo[2..3]; // a fat pointer with length 1 bar[0] = 'C'; printf(foo); // abCd bar[1] = 'D'// ERROR!!! bar has length 1 Note that the array `foo` is now bounds-checked, which may affect backwards-compatibility. Also, `bar` is no longer null-terminated, which means you can't do printf on it.
- acehreli 8y agoPerfectionism is not engineering. Not finding a way to fix every use case that you can come up with is not an excuse to insist on unsafe features that are proven to be disasters in practice.