0

I'm creating my own vector class(for an assignment) here:

private:
T *items;
int used;

Vector() {
    used = 0;
    items = new T[1000];
};

When I construct the vector and use:

std::cout<<sizeof(items)/sizeof(T);

It returns 1 always, no matter what size I make items in the constructor(I've tried 1000,4,1,0,-1) it always cout's 1. I also try to double the array when it reaches 1000, then 2000 then 4000 etc.

        if(used == sizeof(items)/sizeof(items[0])) {
        T *tempItems = new T [used];
        memcpy(items, tempItems, sizeof(items));
        delete []items;
        T* items = new T[used*2];

        memcpy(tempItems, items, sizeof(items));

        delete []tempItems;
        }

It throws an invalid read when I try to print out items's contents. This may be due to the previous problem. I cannot go back to using vector's, that's the point of the assignment.

user3475821
  • 69
  • 1
  • 1
  • 5
  • 4
    `sizeof(items)` == `sizeof(T*)` is a compile-time constant. You need to keep track of the size yourself. – Mat May 16 '15 at 06:20
  • I changed sizeof(items)/sizeof(T) to sizeof(items)/sizeof(string) and it still returns 1 unfortunately. – user3475821 May 16 '15 at 06:30
  • Again, `sizeof(items)` is a constant, returns the size of a pointer to T. You need to keep track of the size yourself. You cannot use sizeof for this. – Mat May 16 '15 at 06:31
  • So how would I get the sizeof(items) for the purposes of memcpy? if items can be any type then how would I grab the total memory of it for the purposes of memcpy? You were completely correct about sizeof and I've made an int size and it doubles when we need to copy but that's an int not what I need unfortunately again. Thanks in advance – user3475821 May 16 '15 at 06:56
  • If you have the size of one item, and the count of items, you've got all you need. But beware, using memcpy to copy C++ objects around is, in general, illegal (in particular, destructors and constructors don't run when you do that). – Mat May 16 '15 at 07:07

0 Answers0