1

this is my code:

void init_array(int** array) {

  *array = (int*) malloc(3 * sizeof(int));

  /* ???? **(array+2) = 666; */

  return;
}

void init(int* array, int* length) {

  *length = 3;

  *(array+0) = 0;
  *(array+1) = 1;
  *(array+2) = 2;

  return;

}

int main(void) {

  /* Variables */

  int array_length;
  int* array;

  /* Initialize */

  init_array(&array);
  init(array, &array_length);

  free(array);

  return 0;

}

My question is: How can I initialize values of the array in a function init_array().

I have attempted things such as:

  • **(array+2) = 666;
  • *(*(array+2)) = 666;
  • *array[2] = 666;
  • **array[2] = 666;

When I used pencil and paper I came to result that **(array+2) should work but it gives me a segmentation fault.

I would appreciate your answer because I am confused how pointers in C actually work.

4
  • 2
    try (*array)[2] = 666; and compile with all warnings on. Commented May 24, 2017 at 14:51
  • I'm familiar with C++ but I thing you need to use the new operator or what ever to declare an object and then create the values in the specified address. Commented May 24, 2017 at 14:52
  • there's no new in C. Commented May 24, 2017 at 14:52
  • Oh alright Jean, wasn't sure! Commented May 24, 2017 at 14:52

1 Answer 1

3

You have the address of a pointer passed to the function:

array

You want to dereference that to get the pointer:

*array

Then apply the array subscript operator to the result:

(*array)[2]

Or equivalently:

*((*array) + 2)

The parenthesis are required because the array subscript operator [] has higher precedence than the dereference operator *.

Generally speaking, you should use the array subscript operator whenever possible, as it tends to be easier to read.

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

Comments

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.