Suppose I have below program,
typedef struct xyz
{
int abc[6];//int abc;
//int yz;
}xyz;
int main()
{
int *ptr = new int(10);
int *ptr1 = new int(20);
xyz* XYZ = reinterpret_cast <xyz*>(ptr); //Initializes XYZ->abc[0]
XYZ = reinterpret_cast <xyz*>(ptr1);//Initializes XYZ->abc[0]
}
Here the value enters into zeroth location. If I would like to push the value into XYZ->abc[1], then how can I do this?
Maybe you want to do
But this kind of code is disgusting, it probably is an undefined behavior (because
ptr1+1might not be a valid location, and you could get a segmentation fault), so you should avoid doing that.I actually don’t understand the motivation (and use case) of your question.
Maybe you wanted to allocate ten ints on the heap. Then code
and don’t forget to initialize them, e.g. with
memset (ptr, 0, sizeof(int)*10);On Linux systems, I strongly suggest to compile with
g++ -Wall -gand to use valgrind andgdbto debug your program. You really want to know these tools.