Arrays With Padding

Sep 14, 2011 at 8:31pm
closed account (zb0S216C)
I'm trying to create a class that constructs and manages a region of memory. The region of memory is an array, where each element has n bytes between them (padding).

Here's a diagram I made: http://postimage.org/image/qsun6ojo/ The diagram demonstrates how the array should look im memory.

Here's my issue: I don't know how to perform the computation to access each element individually with a for loop. Any ideas?

Wazzak
Last edited on Sep 14, 2011 at 8:32pm
Sep 14, 2011 at 8:57pm
how do you want to access the fields? pointer? index?
Sep 14, 2011 at 9:07pm
closed account (zb0S216C)
I'll use pointer arithmetic behind the scenes but allow the client to pass an index. Say, for example:

1
2
3
4
int &Access( int Index )
{
    return *( Pointer + ... );
}


Wazzak
Sep 14, 2011 at 9:32pm
closed account (zb0S216C)
I may have solved it. Here's my test code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
int main( )
{
    int SizeofElement( 4 );
    int ElementCount( 5 );
    int SizeofPadding( 1 );
    int *Region( nullptr );

    Region = ( int * )malloc( ( ElementCount * SizeofElement ) + ( SizeofPadding + ( ElementCount - 1 ) ) );

    if( Region == nullptr )
    {
        std::cout << "Allocation failed" << std::endl;
        return 1;
    }

    int Block( SizeofElement + SizeofPadding );
    for( int i( 0 ); i < ElementCount; i++ )
    {
        *( Region + ( i * Block ) ) = ( i + 1 );
        std::cout << *( Region + ( i * Block ) ) << std::endl;
    }

    free( Region );
    Region = nullptr;

    return 0;
}

Note that I had to use std::malloc( ) so I could incorporate padding. Since this is a test code segment, it's open to modification and suggestions. How could I improve this?

Wazzak
Topic archived. No new replies allowed.