3 ms·
> How do I get the size, sizeof(array) > the number of elements? array.length > Can I resize the array? If yes, how? If no, why? In D it would be:
by WalterBright 6y ago
> How do I get the size,
sizeof(array)
> the number of elements?
array.length
> Can I resize the array? If yes, how? If no, why?
In D it would be:
T* p = realloc(array.ptr, newLength * sizeof(T));
array = p[0 .. newLength];
A C macro could handle that in C.
> What happens if I overflow?
2's complement arithmetic happens.
> A memcpy-like would be an obvious function to implement, what happens if sizes differ?
That would be up to the implementor of the function. There are many ways.
> What is the relationship between static arrays (ex: int a[5]) and "pointer+size" arrays? Are these completely different types?
Yes, they are different types.
> Is there an implicit cast bet>ween the two?
Conversion between a static array and the dynamic array should be implicit. Can't go the other way.
> About casting, how can I go from a separate pointer and size to an array and vice versa? If it is possible at all.
In D, this would be:
a = p[0 .. size];
In C, I expect a macro can do it:
a = ToArray(p, size);
> What if I do a bit of pointer magic to access the internal representation of the array?
Then you'd need to be careful to do it right, as in any systems language when you go under the hood.
> using mem* instead of str*
That only works for some functions. Not fopen(), for example.
> or %.*s
I use that a lot, but it's annoying because the length argument must be an int, and so must be cast from size_t.