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

前端 未结 4 1075
栀梦
栀梦 2021-02-04 05:30

I have the following code:

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

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

4条回答
  •  孤独总比滥情好
    2021-02-04 06:10

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

提交回复
热议问题