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
2
  • 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. Commented Oct 6, 2015 at 8:06
  • 1
    Remember the spiral rule: c-faq.com/decl/spiral.anderson.html Commented Oct 6, 2015 at 8:45

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

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.
Then change your compiler. In C, you don't cast malloc, its not C++!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.