develop dynamic buffer/memory


1
2
3
unsigned int* buffer;
buffer = new() unsigned int[24];


I want to access 24 locations as 3 arrays of 8 bytes

Like want pointer to point on 0th, 8th, and 16th locations and respective 8 locations in each case 0-7, 8-15, 16-23 array accessed.

I want to use some concept like pointer of arrays and dynamically allocate memory for all.
Use typedefs to help.
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
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
#include <iomanip>
#include <iostream>
using namespace std;

int main()
  {
  // It is convenient to use typedefs to simplify your complex array type
  // (Sometimes it is necessary, but it isn't in this case.)
  typedef unsigned char byte;
  typedef byte eight_bytes[ 8 ];
  
  // Here's our prototype in the nice, easy-to-read way (using our typedefs)
  void print( eight_bytes*, unsigned );
  
  // Here we get our data from the heap
  // (But you could get it from anywhere, I guess...)
  eight_bytes* three_of_eight = new eight_bytes[ 3 ];

  // Lets set the array to be filled with numbers of the form: i 0 j
  for (unsigned i = 0; i < 3; i++)
  for (unsigned j = 0; j < 8; j++)
    three_of_eight[ i ][ j ] = i*100 + j;

  // Elephant, duh.
  print( three_of_eight, 3 );
  
  // Don't forget to clean up
  delete [] three_of_eight;

  return 0;
  }

// Here's our function without the nice, fancy typedefs to make life pretty
void print( unsigned char a[][ 8 ], unsigned size )
  {
  cout << setfill( '0' );
  for (unsigned n = 0; n < size; n++)
    {
    for (unsigned m = 0; m < 8; m++)
      cout << setw( 3 ) << (int) a[ n ][ m ] << " ";
    cout << "\n";
    }
  }
000 001 002 003 004 005 006 007
100 101 102 103 104 105 106 107
200 201 202 203 204 205 206 207

Remember, the pointer on line 17 need not be aimed at memory on the heap. You could easily aim it at something simple, like a flat (1D) array with your data, or whatever it is you want to access the bytes of.

32
33
34
35
36
37
38
39
40
                  //012345670123456701234567
  char message[] = "Earth laughs in flowers.";
  
  three_of_eight = (eight_bytes*)message;
  
  print( three_of_eight, 3 );

  return 0;
}
069 097 114 116 104 032 108 097
117 103 104 115 032 105 110 032
102 108 111 119 101 114 115 046


Hope this helps.
Topic archived. No new replies allowed.