C: Cannot initialize variable with an rvalue of type void*

user3662185 picture user3662185 · Jun 15, 2014 · Viewed 73.6k times · Source

I have the following code:

int *numberArray = calloc(n, sizeof(int));

And I am unable to understand why I receive the following error.

Cannot initialize a variable of type 'int *' with an rvalue of type 'void *'`.

Thank you.

Answer

R Sahu picture R Sahu · Jun 15, 2014

The compiler's error message is very clear.

The return value of calloc is void*. You are assigning it to a variable of type int*.

That is ok in a C program, but not int a C++ program.

You can change that line to

int* numberArray = (int*)calloc(n, sizeof(int));

But, a better alternative will be to use the new operator to allocate memory. After all, you are using C++.

int* numberArray = new int[n];