Using XOR with pointers in C

Last week, our teacher gave us the task of making a double linked list in C without using two pointers in the structure; we must implement it simply using one pointer to point to the next and previous node in the list. I am convinced that the only way to do this is to use XOR to combine the next and previous directions, and then point to this “hybrid” memory allocation, and if I need the directions of the previous or next, I can use XOR again to get one of the memory values, which I need.

I developed an algorithm, and I thought it would work, but when I tried to implement this solution, I ran into a problem. When I tried to compile the program, the compiler told me that I cannot use XOR (^) for pointers:

invalid operands to binary ^ (have ‘void *’ and ‘node *’)

Here is the function to add node to the top of the list:

typedef  struct node_list{
  int data;
  struct node_list *px;
}  node;

node* addfront ( node *root, int data ){ 
  node *new_node, *next;

  new_node = malloc ( sizeof ( node )); 
  new_node -> data = data;

  new_node -> px = (NULL ^ root);//this will be the new head of the list

  if ( root != NULL ){           // if the list isn't empty
    next = ( NULL ^ root -> px );  // "next" will be the following node of root, NULL^(NULL^next_element).
    root = ( new_node ^ next );    //now root isn't the head node, so it doesn't need to point null.
  }
}

I read that in C ++, XOR characters are valid. Any ideas on how to implement this in C? I also read somewhere that I need to use intptr_t, but I did not understand what to do with it.

+4
source share
1 answer
#include <stdint.h>

(void *)((uintptr_t)p1 ^ (uintptr_t)p2)

, C , void * uintptr_t; (uintptr_t)p1 ^ (uintptr_t)p2 ( X) uintptr_t , (void *)X, (void *)X uintptr_t, X, , .

, , uintptr_t, void * " xor". :

uintptr_t xor_ptr = (uintptr_t)p1 ^ (uintptr_t)p2;

p1 p2 ( ) :

(void *)(xor_ptr ^ (uintptr_t)p2)

xor_ptr ^ (uintptr_t)p2 (uintptr_t)p1, C uintptr_t , , void *, ( ) p1 ( C11 7.20.1.4).

+10

All Articles