Home > Software design >  Pointer modification
Pointer modification

Time:08-10

How to go to a location with pointer addition and change the pointer at that position to point to a new address?
The following code is just an example, I do not want an easy way as just do ptr[1] = (new addr)
but to change the address with the following method:

  1. create a new pointer variable
  2. go to designated address with pointer addition
  3. change the pointer on that address to point to new address
int *ptr[5]; 
void *p = &(ptr[0])   sizeof(int*);  
*p = (void*)(uintptr_t)(new address);

CodePudding user response:

    int *ptr[5]; 
    void *p = &(ptr[1]);  
    &p = (void*)(uintptr_t)(new address);

Is this what you are looking for?

CodePudding user response:

Void-pointers are a great way to shoot yourself in the foot, since the compiler won't be able to do much error-checking for you, but if you insist on using them:

#include <stdio.h>

int main(int argc, char ** argv)
{
   void * ptrs[5] = {NULL, NULL, NULL, NULL, NULL};
   void **p = ptrs 1;
   *p = (void*)((uintptr_t)(0x666));

   for (int i=0; i<5; i  ) printf("  ptrs[%i] is %p\n", i, ptrs[i]);
   return 0;
}

Running the above program yields this output:

ptrs[0] is 0x0
ptrs[1] is 0x666
ptrs[2] is 0x0
ptrs[3] is 0x0
ptrs[4] is 0x0

CodePudding user response:

This version is probably overkill...

int main() {
    union {
        void *p;
        unsigned long x;
    } foo;

    int a = 5;
    int b = 42;

    int *arr[] = { &a, &b };

    printf( "Before %d\n", *arr[1] );

    foo.p = &arr[0];
    foo.x  = sizeof(int*);

    printf( "Still %d\n", *(*((int**)foo.p )) );

    *(*((int**)foo.p )) = 27;

    printf( "After %d\n", *arr[1] );

    return 0;
}

Output

Before 42
Still 42
After 27
  • Related