Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 888
user3662185 Avatar asked Jun 15 '14 08:06

user3662185


1 Answers

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 in 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];
like image 40
R Sahu Avatar answered Nov 10 '22 10:11

R Sahu