verito verito - 3 months ago 20
C Question

Complex numbers 3D array

How do I define three dimensional array of complex numbers dynamically in C so that I can access in

[i] [j] [k]
notations which is handy in accessing arrays?

alk alk
Answer

Extending Bob__'s example to have the array allocated on the heap instead of on the stack:

#include <stdlib.h>
#include <stdio.h>
#include <complex.h>


int main(void) 
{
  size_t n = 2, m = 3, o = 4;

  double complex (*pa)[n][m][o] = malloc(sizeof *pa);
  if (NULL == pa)
  {
    perror("malloc() failed");
    exit(EXIT_FAILURE);
  }

  (*pa)[1][2][3] = 1.0 + 0.5*I;

  printf("%f + %fi\n", creal((*pa)[1][2][3]), cimag((*pa)[1][2][3]));

  free(pa);

  return EXIT_SUCCESS;
}