0

I'm maintaining a part of code written by my friend, here's a definition of a variable called d:

double (*d)[3];

I tried to initialize the variable using the code below but in each part there is an error (runtime or compilation). I have gotten confused whether variable d is a pointer to array of double or array of pointers to double.

double k;
(*d)[0] = k; // runtime error using gcc compiler
d[0] = &k;   // Compilation error, assignment to expression with array type
*d = &k;     // Compilation error, assignment to expression with array type
undur_gongor
  • 15,657
  • 5
  • 63
  • 75
  • It would help if you tagged the programming language. Yes, there are people who will recognise the language just from the code. But not everyone will do that. – Peter Oct 06 '15 at 08:06
  • 1
    Remember the spiral rule: http://c-faq.com/decl/spiral.anderson.html – ChronoTrigger Oct 06 '15 at 08:45

1 Answers1

4

The d variable is a pointer to a 3 length double array. So you can assign a pointer of a double[3] array to it. For example:

double (*d)[3];
double a[3] = {1.0, 2.0, 3.0}
d = &a; 

But to make it more practical, you can also use dynamic memory allocation. For example:

double (*d)[3];
d = malloc(3 * sizeof(double));
d[0][0] = 1.0;
d[0][1] = 2.0;
d[0][2] = 3.0;
printf("%f %f %f\n", d[0][0], d[0][1], d[0][2]);

This way, d will point to a single, 3-length double array. The program will give the following output:

1.0 2.0 3.0

By the way, you can replace e.g. d[0][0] with (*d)[0], they mean exactly the same.

meskobalazs
  • 15,741
  • 2
  • 40
  • 63
  • Great answer. Something I want to add is casting `malloc` output ( pointer to double ) is not perform implicitly in my `DEV` compiler. And I had to use `d = (double (*)[3]) malloc (3 * sizeof(double));` instead. – Mehrshad Lotfi Foroushani Oct 08 '15 at 20:43
  • 1
    Then change your compiler. In C, you don't cast malloc, its not C++! – meskobalazs Oct 08 '15 at 21:00