-1

See the following code:

#include <iostream>
#include <stdlib.h>

using namespace std;

class ex
{
 public:
    int x;
    int y;
    double z;
    ex()
    {
     cout<<"constructor";
    }
    ~ex()
    {
         cout<<"destructor";
    }
};

int main()
{
   void *pt=malloc(sizeof(ex)*2);

   ex *p,*p1;
   p=new(pt) ex();
   p1=new(pt+sizeof(ex)) ex();
   p->x=4444;
   p->y=3333;
   p->z=65.87879898;
   p1->x=55555;
   p1->y=66666;
   p1->z=6666.6666666;
   cout<<"\nP: "<<p->x<<"\n"<<p->y<<"\n"<<p->z<<"\n";
   cout<<"\np1: "<<p1->x<<"\n"<<p1->y<<"\n"<<p1->z<<"\n";
   p->~ex();
   p1->~ex();

   free(pt);
   return 0;
}

It shows warning. warning: pointer of type 'void *' used in arithmetic [-Wpointer-arith]|

There is any way to overcome that or the code is wrong. note:That code displays correct output.

Thank you for helping.

srilakshmikanthanp
  • 2,231
  • 1
  • 8
  • 25

1 Answers1

4

This line is problematic:

pt+sizeof(ex)

Since pt is a void* it's not known what the size of one element is. Some compilers will compile it as if the size were 1, which makes your code run successfully. But this is not standards compliant. Instead, do this:

p+1

That is, use the memory address which is one element (of type ex) after the first one.

Or, cast to char* so you know you're operating with elements of size 1:

static_cast<char*>(pt)+sizeof(ex)
John Zwinck
  • 239,568
  • 38
  • 324
  • 436