Home > Software design >  Pointer to an element of a 2D Array in C
Pointer to an element of a 2D Array in C

Time:11-24

I am getting confused again by the pointer principle.

I have the following two arrays a and b:

int16_t a[3][2] = {

  {30,  40},
  {31,  41},
  {32,  42}
};

int16_t b[3][2] = {

  {50,  40},
  {51,  41},
  {52,  42}
};

The second column of b shall always be equivalent to the second column of a. So whenever a changes on the second column (e.g. 40 getting 60), this should be represented in b as well.

So I am looking for something like that using a pointer but could not make it work:

int16_t a[3][2] = {

  {30,  40},
  {31,  41},
  {32,  42}
};

int16_t b[3][2] = {

  {50,  (*a[0][1])},
  {51,  (*a[1][1])},
  {52,  (*a[2][1])}
};

I am not too familiar with the pointer principle. Any suggestions?

CodePudding user response:

b's elements should be pointers if you want to achieve this. In that case you can set the elements of second column of b to point to their corresponding elements in array a.

So your code can be written like this:

int *b[3][2] = {
         {new int(50), (&a[0][1])},
         {new int(51), (&a[1][1])},
         {new int(52), (&a[2][1])}
};

Be aware that this can lead to memory leaks if you don't remember to delete the elements that are created using new. This can be avoided by using another array for initialization of the first column of b.

With this solution you'll have to use the * operator to see values of elements of b. for example:

std::cout << *b[0][0] << std::endl;

A rather simpler solution would be implementing a function to update both of the array together. This can simplify the process of working with and using elements of b, but it's performance is a bit worse since the updating process can take double time as the first solution.

CodePudding user response:

You immediately indirect through the pointer, and store the copy of the pointed integer in the array. Changes to the original have no effect on the copies. Since the b array is an array of (arrays of) integers, its elements cannot point or refer to anything; they aren't pointers nor references.

If you want one value to reflect another, you need indirection. Pointer would be the choice in this case since references cannot be array elements. Here is an example where b is an array of (arrays of) pointers to integers

std::int16_t b0[] = {
  50,
  51,
  52,
};


std::int16_t* b[][2] = {
  {b0   0,  a[0]   1},
  {b0   1,  a[1]   1},
  {b0   2,  a[2]   1},
};

You could alternatively define a special "variant"-like class that alternatively stores the integer, or refers to an integer transparently. But that would be a lot of boilerplate and I'm not convinced it would be worth the effort.

  • Related