T
T
tarasrm2020-11-15 20:32:51
C++ / C#
tarasrm, 2020-11-15 20:32:51

Is it possible in C to replace X[i][j] with *((X+i)+j)?

Is it possible to replace X[i][j] with *((X+i)+j) ?
This is the same?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Alexey_Alive, 2020-11-17
@tarasrm

No. This is how you can *((X+i*j)+j)

W
wisgest, 2020-11-25
@wisgest

No, one character is missing *: in C, X[i][j]you can replace with *(*(X + i) + j)(and also with *(X[i] + j)or (*(X + i))[j]).
In this case , it Xcan be (in brackets it is indicated in which cases the entry is appropriate X[i][j]):
a) an array of arrays;
b) a pointer to an array (which is the 0th element of a dynamic array of arrays);
c) an array of pointers (to the 0th elements of dynamic arrays);
d) pointer to a pointer (to the 0th element of a dynamic array of pointers to the 0th elements of dynamic arrays).

Example
#define TElem int
#define M 2
#define N 3

TElem a[M][N]               // массив массивов
   = {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}};
TElem (*b)[N] = &a[0];      // указатель на массив
TElem *c[M] = {a[0], a[1]}; // массив указателей
TElem **d = &c;             // указатель на указатель

#include <stdio.h>
int main(void) {
  TElem x;
  #define i 1
  #define j 2

  puts("X[i][j]");
  x = a[i][j];  printf("%d\n", x);
  x = b[i][j];  printf("%d\n", x);
  x = c[i][j];  printf("%d\n", x);
  x = d[i][j];  printf("%d\n", x);

  puts("(*(X + i))[j]");
  x = (*(a + i))[j];  printf("%d\n", x);
  x = (*(b + i))[j];  printf("%d\n", x);
  x = (*(c + i))[j];  printf("%d\n", x);
  x = (*(d + i))[j];  printf("%d\n", x);

  puts("*(X[i] + j)");
  x = *(a[i] + j);  printf("%d\n", x);
  x = *(b[i] + j);  printf("%d\n", x);
  x = *(c[i] + j);  printf("%d\n", x);
  x = *(d[i] + j);  printf("%d\n", x);

  puts("*(*(X + i) + j)");
  x = *(*(a + i) + j);  printf("%d\n", x);
  x = *(*(b + i) + j);  printf("%d\n", x);
  x = *(*(c + i) + j);  printf("%d\n", x);
  x = *(*(d + i) + j);  printf("%d\n", x);

  return 0;
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question