Array access via pointer

Pelle pelle.mansson at gmail.com
Sun May 30 22:50:27 PDT 2010


On 05/30/2010 11:54 PM, Robert wrote:
> On 2010-05-30 23:12:06 +0200, "Simen kjaeraas" <simen.kjaras at gmail.com>
> said:
>
>> Going again with the C code:
>>
>> typedef struct array {
>> int* data;
>> int length;
>> };
>>
>> You would use an array like this:
>>
>> void foo( ) {
>> array arr;
>> arr.ptr = malloc(32);
>> arr.length = 8;
>> }
>>
>> Now, as you can probbly see, &arr would give the pointer to the
>> struct, not to the data. Basically, a pointer to pointer to int,
>> rather than the pointer to int you want.
>
> Ok, I thought that the structure was a bit more flat like:
>
> typedef struct array {
> int length;
> int[1..length] data;
> }
>
> Avoiding one indirection as it could be assumed that the
> memory-allocator / GC will return a continous piece for the array. But
> of course resizing and reallocation would be a bit more complicated.
>

Not avoiding an indirection if it's still located on the heap. I mean, 
pointer to (length and array), or (pointer and length) to array. Still 
just one level of indirection.

The fat pointer solution also allow for arbitrary slicing.


More information about the Digitalmars-d mailing list