1

I encountered erratic behavior when initializing array in function.

I have an uninitialized pointer below:

int *arr;

And I am passing it to a function for initialization.

init_arr(&arr);

void init_arr(int **arr)
{
*arr = (int *) calloc(10, sizeof **arr);
}

The pointer is initilized, and when I try get items *arr[2] and larger I get the error:

Cannot access memory to address 0x0

The source code was compiled using gcc version 4.8.4

5
  • get item (*arr)[2] perhaps? Commented Oct 25, 2015 at 23:50
  • Try (*arr)[2] and this works! thanks! I need to be careful. Thanks again! Commented Oct 25, 2015 at 23:57
  • I am not sure, but believe (*arr)[2] is equivalent to just arr[2], as the compiler treats a pointer as an array. Commented Oct 26, 2015 at 0:00
  • do not cast the returned value from calloc() why? because 1) the returned value is a defined as void * so can be assigned to any other pointer. 2) the cast just clutters the code and can create a real headache when debugging or maintaining the code. Commented Oct 26, 2015 at 0:43
  • user3629249, I will turn attention to it. Thanks Commented Oct 26, 2015 at 13:47

1 Answer 1

1

Instead of expression

 *arr[2]

you have to use

 arr[2]

You allocated an array of 10 integers. So to acces an element of the array it is enough to write for example arr[2].

If you mean an access of an element of the allocated array inside the function init then you have to write

 ( *arr )[2]
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.