3

I have this piece of code that allocates and creates 5 objects of type MyClass:

#include <iostream>     
#include <new>             
struct MyClass {
  int data;

};

int main () {

  struct MyClass *p1=new MyClass[5];
  p1->data=42;

  return 0;
}

So,if i understand this correctly p1 is a pointer to a memory location of size Myclass[5] where these 5 objects are stored.So by using p1->data=42 is the int data updated for each of 5 objects.If so,how can i update data individually for a specific object?(Let's say the 3rd one)

  • 1
    `p1->data` applies to the first object only. You want `p1[i].data`. – HolyBlackCat May 19 '19 at 21:57
  • @HolyBlackCat p1[2].data=4; is possible even if p1 is a pointer? – Epitheoritis 32 May 19 '19 at 22:07
  • Hi @Epitheoritis 32, p1 is a pointer the bracket [dereferences the pointer](https://stackoverflow.com/questions/4622461/difference-between-pointer-index-and-pointer) so you can treat is like an object. – lakeweb May 19 '19 at 22:48
  • @Epitheoritis32 Yes. In fact, it *only* works on pointers (if we don't consider overloaded operators). When you apply it to an array, the array is converted to a pointer first. – HolyBlackCat May 20 '19 at 07:30

2 Answers2

3

Update: If you allocate yourself, as HolyBlackCat says:

p1[i].data = 42;

Bu if this is not an assignment and you don't have to use new...

#include <vector>
struct MyClass {
    int data;

};
using MyClassVect_type = std::vector<MyClass>;

int main() {

    MyClassVect_type my_5(5);

    my_5.at(0).data = 37;
    my_5.at(1).data = 42;
    //or
    my_5[2].data = 13;
    //etc....

    return 0;
}
lakeweb
  • 1,859
  • 2
  • 16
  • 21
2

So by using p1->data=42 is the int data updated for each of 5 objects.

Incorrect. p1 points to the first of those 5 objects. So, p1->data=42 assigns only the member of the first object.

how can i update data individually for a specific object?

You can use the subscript operator to access the sibling objects: p1[i].data = 42 assigns the member of the ith object in the array.


P.S. The example program leaks the allocated memory.

P.P.S. It is not necessary to include the header <new> in order to use the new-expression.

eerorika
  • 232,697
  • 12
  • 197
  • 326
  • What do you mean by saying leaks the allocated memory? – Epitheoritis 32 May 20 '19 at 12:32
  • @Epitheoritis32 Objects created using a `new`-expression are not automatically destroyed. They must be explicitly `delete`d. If the pointer returned by `new` is lost before the object is deleted through it, it can never be deleted. This is called a memory leak. – eerorika May 20 '19 at 12:35