Search code examples
cpointersvariable-initialization

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.


Solution

  • 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];