1

I know a contiguous block of memory is allocated for an array.

My first question is when the array element is an object rather than a built-in type, what gets stored in the contiguous memory reserved for the array? Pointer for the object or the actual data for the object? My guess is pointers are stored in the array and the actual objects are stored randomly in the heap. Am I correct?

My second question is now we want to reserve a specified memory(e.g., shared memory) for an array of objects. What is the best way to achieve this? Should I serialise the actual objects in the specified memory one by one and use relative pointers(e.g., indices) to access each of them?

Terry Li
  • 16,870
  • 30
  • 89
  • 134

4 Answers4

5

Not at all correct. An array T[N] contains N elements of type T, directly stored in contiguous memory. The array occupies N * sizeof(T) bytes of memory.

Conversely, to answer your second question, any run of N * sizeof(T) bytes of memory can be used to hold N elements of type T (subject to some alignment constraints perhaps).

Kerrek SB
  • 464,522
  • 92
  • 875
  • 1,084
0

No, the objects are stored unless you have an array of pointers. Generally, c++ does what you ask for and takes no liberties.

Storing the objects in shared memory depends on the nature of your objects, you basically better stick to plain data, I think.

Michael Krelin - hacker
  • 138,757
  • 24
  • 193
  • 173
0

Nope, the objects themselves are stored. The name of the array just gives you a pointer to the first element, which you can then use pointer arithmetic on to traverse the array.

MGZero
  • 5,812
  • 5
  • 29
  • 46
  • 3
    If at all, then the name of the array gives you a reference to the array. This *may* under certain circumstances decay to a pointer to the first element. – Kerrek SB Nov 28 '11 at 15:37
0

I would say I depends on kind of source code of an object.

class an_my_object_a {
    private:
    something_t something;
    something_else_t something_else;
    third_field_t third_field;
    public:
    //there are some methods
}

class an_my_object_b {
    private:
    an_my_object_a * d;
    public:
    //there are some methods
}

The array of an_my_object_a may store all its data in continuous memory. The array of an_my_object_b is practically an array of pointers.

Michas
  • 8,534
  • 6
  • 38
  • 62