I hope this helps:
int x = 2;
int *ptr = &x; //ptr points to address of x. yes correct.
int y = 3;
&y = ptr + 1; //the address of next integer after x(internally,
// which is ptr) will be set to address of y(this
// won't work.)
on the last line, if your intention is make y
become the storage that is internally next to x
, this won't happen because int y
is a declaration that y
will be data holder and won't move it's address. it's address is fixed forever.
in addition, this is the internal memory based on your code.
[ 1 byte ] //4 bytes for integer x
[ 1 byte ]
[ 1 byte ]
[ 1 byte ]
[ 1 byte ] //4 bytes for address holder ptr (in 32bit system)
[ 1 byte ]
[ 1 byte ]
[ 1 byte ]
[ 1 byte ] //4 bytes for integer y
[ 1 byte ]
[ 1 byte ]
[ 1 byte ]
you can change y
via x
by treating it as an array.
(&x)[2] = 100; //setting 100 to y indirectly.
note: this might not work on different compilers due to internal optimizations, so it's a dangerous type of code if you use it on real world projects. but you can 100% use it for fun and exploration. one way to love programming more.
another crazier example.
(&x)[1] = 0x123498; //setting any address value to ptr.
(&x)[1] = &y; //setting address of y to ptr.
to your original question(i hope i get it)
So, what are some other ways I can exploit to be able to create my own array?
to "create" your own array, or let's say create dynamically at runtime, you have to allocate first a sequence of bytes that will fit to the array of the size you need. and then access the elements or any kind of manipulation via pointer or reference.
//---allocate using malloc and free.
int *pIntBuffer = (int*)malloc( 500 * sizeof(int)); //request chunk of memory.
pIntBuffer[10] = 123; //use the array any way you want.
free(pIntBuffer); //be sure to destroy your requested chunk of memory if you don't need it anymore.
//---allocate using new/delete.
int *pAnotherBuff = new int[1000];
pAnotherBuff[900] = *pIntBuffer[10];
delete [] pAnotherBuff;