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

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

    void* calloc (size_t num, size_t size);
    

    Allocate and zero-initialize array. Allocates a block of memory for an array of num elements, each of them size bytes long, and initializes all its bits to zero.The effective result is the allocation of a zero-initialized memory block of (num*size) bytes.

    On success, a pointer to the memory block allocated by the function. The type of this pointer is always void*, which can be cast to the desired type of data pointer in order to be dereferenceable. If the function failed to allocate the requested block of memory, a null pointer is returned.

    To summarize, since calloc returns a void* (generic pointer) on success of memory allocation, you will have to type-cast it like this in C++:

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

    If it was C, you can still skip this cast.

    Or, use new as:

    int *numberArray = new int [n];
    

提交回复
热议问题