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

前端 未结 4 1130
栀梦
栀梦 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:03

    You're using C memory re-allocation style in a C++ code. What you want to use is new in C++

    So your code will become:

    int n = 10; //n = size of your array
    int *narray = new int[n];
    for (int i = 0; i < n; i++)
        cout << narray[i];
    

    Alternatively you can switch back to C and use calloc with casting.

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

提交回复
热议问题