Home > front end >  Is it possible to intricate pointers in C?
Is it possible to intricate pointers in C?

Time:10-28

Something recently hyped my curiosity while coding : is it possible to intricate pointers in C ? I explain: I would like to link two pointers, let's say two int * p1 and p2. The idea is, whenever I edit the value of p1, the value of p2 is also edited. Example :

  • *p1 = 2 and I want for instance that *p2 = *p1-1;
  • *p1=3;. But here *p2 still amounts to 1... Is there a way to make *p2 equals to *p1 - 1 every time, without having to edit the value of *p2 after every modification of *p1 ?

Not having to edit intricated pointers every time.

CodePudding user response:

Short answer is no.

There isn't "magic under the hood" with pointers. I know that, when beginning, it may seems so. Because of the apparent magic of things like

int x=12;
int *y=&x;

*y=15; // Wow, value of x has changed

But in reality those are really rudimentary things. With absolutely no other operation than the plain operations we wrote. y is the "address" of x. *y=15 changes what is at address y, that is, since this is the value of y, what it at the address of x. So it changes x.

It is not like in higher level languages, such as python, or even C , where you could have redefined affectation operators, or things like that, so that the simple fact of saying *y=15 does way more things than changing what is at address y, but also affects other values. Understand that something will have to computes 15-1 to do what you want. Those computations have to be done somewhere. In higher level languages, they could be implicit, because you said, somehow, that = implies many such computations. But in low-level language, the only computations that occurs are the one you explicitly coded.

So, again, short answer: no, not in C.

CodePudding user response:

Don't use separate pointers but pointer arithmetic:

#include<stdio.h>

int main (void)
{
  int array [3] = {1,2,3};
  int* p1 = &array[1];
  const int offset = -1;
  printf("p1: %d p2: %d\n", *p1, p1[offset]);

  p1 = &array[2];
  printf("p1: %d p2: %d\n", *p1, p1[offset]);
}

This is fine and well-defined as long as the offset doesn't lead to an out of bounds access.

  • Related