Pointers to a class with attribute Vector

Oct 15, 2009 at 3:18pm
Hello all,

Am stuck with pointers concept a bit.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class myclass
{
 stl::vector<double> list;
};

main()
{
myclass *myptr;

/* create 100 objects of type myclass */
myptr = new myclass[100];

/* have I used 'delete' correctly? */
delete [] myptr;
}


Q.1 I assume myptr would point to first object of type myclass, lets name it myclass[0]. Is it true?

Q.2 If I increment myptr, i.e.
myptr = myptr+1;
will it point to next object myclass[1]. If the answer is Yes, then Questions.3&4 make sense together!

Q.3 Vectors can have "unlimited" size. So what would be the "size" of an object of class myclass? (Possible answer could be that, internally this vector element is stored as a pointer to a list of double elements. So still the size of the object is fixed!)

Q.4 Suppose int is size 4. If I have a pointer to int, and I increment it, the pointer internally increments address by 4. But vectors have indefinite size, how would the increment happen?

Kindly advice!
Oct 15, 2009 at 3:27pm
main() should be int main().
stl::vector should be std::vector

1.) Yes.
2.) Yes.
3.) use sizeof(myclass) (I think it is in bytes)
4.) No, it increments it by 1 word (which is the size of a pointer, which also just so happens to be the size of an int). As for std::vector, I don't really know how it works (I don't read the STL header files lol)

EDIT:It actually increments by sizeof(type).
Last edited on Oct 15, 2009 at 3:46pm
Oct 15, 2009 at 3:31pm
1. Yes.
2. Yes.
3. No. Arbitrary size. To find out the size of an object of type myclass, do sizeof(myclass). This will not calculate the actual size of the std::vector's internal array. sizeof(std::vector) varies with implementation, but it's usually the size of two or three registers, I think.
4. By sizeof(std::vector) which, again, doesn't consider the size of the internal array.

sizeof(T) is calculated at compile time, not run time.

EDIT:
4.) No, it increments it by 1 word
No. If x==0 and x is a T *, then after x++, x==sizeof(T).
Last edited on Oct 15, 2009 at 3:35pm
Oct 15, 2009 at 3:42pm
Thanks Friedraco.

Regarding Q.4, I doubt that it would increase by 1 word. It depends upon the size of object the pointer is pointing to. Just take the example from Q2.

Suppose myptr = 100 and sizeof(myclass)=20
myptr = myptr+1;

then myptr will contain value 120....
Oct 15, 2009 at 3:47pm
Thanks Helios! Just one thing is unanswered, does this delete statement work?

delete [] myptr;

I dont know why but when my program completes execution, then there is always an error message due to some illegal address.
Oct 15, 2009 at 3:59pm
It should work, but only if myptr still points to the beginning of the array.
Topic archived. No new replies allowed.