0

The std :: vector in C++ stores the objects in contiguous memory locations. But when I print the address, I find that this does not happen. Please let me know why. The code is here:

#include <iostream>
#include <vector>
using namespace std;
class a
{

     int val1;

};
vector<a> records(10);
int main()
{
     int i;
     for(i=0;i<12;i++)
         cerr<<"address"<<i<<"="<<&records[i]<<endl;
}

The output I get is not contiguous in memory.

Goz
  • 61,365
  • 24
  • 124
  • 204
Aakash Anuj
  • 3,773
  • 7
  • 35
  • 47
  • The output i get is :address0=0xde0010 address1=0xde0014 address2=0xde0018 address3=0xde001c address4=0xde0020 address5=0xde0024 address6=0xde0028 address7=0xde002c address8=0xde0030 address9=0xde0034 – Aakash Anuj Jun 28 '12 at 06:14
  • 3
    @AakashAnuj, Seems fine to me. Your struct contains one `int`, which is 4 bytes, like most. – chris Jun 28 '12 at 06:15
  • 3
    and why do you iterate in range (0, 11) when the size of vector is 10? – Andrew Jun 28 '12 at 06:15
  • after 18, i get 1c? it should have been address3=0xde0022 right? – Aakash Anuj Jun 28 '12 at 06:17
  • 1
    nope ... 0x18 + 0x4 = 0x1c ... – Goz Jun 28 '12 at 06:17
  • 1
    @AakashAnuj, Addresses are typically displayed in [hexadecimal](http://en.wikipedia.org/wiki/Hexadecimal) form, as evident by the leading `0x`. – chris Jun 28 '12 at 06:18
  • Please read a bit about numeration bases - hexa, decimal, binary – Sam Jun 28 '12 at 06:18
  • I already specified yesterday that it does - http://stackoverflow.com/questions/11227406/assigning-specific-explicit-memory-locations-to-my-objects – Luchian Grigore Jun 28 '12 at 06:52

3 Answers3

7

First of all the memory addressed you show are contiguous - simply the size of an integer is 4 bytes on your system it seems.

Also your vector is of size 10 and you print the addresses up to 12. This is not a problem thanks to the memory allocation strategy of a vector, though. Just keep in mind you should be more careful.

Ivaylo Strandjev
  • 69,226
  • 18
  • 123
  • 176
3

The addresses will be offset from each other by the size of class A.

loki11
  • 374
  • 1
  • 4
2

Because in your system, every int has a size of 4 bytes.

jweyrich
  • 31,198
  • 5
  • 66
  • 97
Pigueiras
  • 18,778
  • 10
  • 64
  • 87
  • 2
    not true. It is implementation defined. See this: http://stackoverflow.com/questions/589575/size-of-int-long-etc – Andrew Jun 28 '12 at 06:16
  • 2
    @Andrew it's generally a better idea to improve the answer, unless the author disagrees with it. And you already got the rep for that. – jweyrich Jun 28 '12 at 06:18