简体   繁体   中英

Initialize values of dynamic array in a function (C language)

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM