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

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

    Syntax for calloc is:

    void* calloc (size_t num, size_t size);

    calloc returns void pointer. In your code , you are trying to assign void pointer to integer pointer. So you are getting Cannot initialize a variable of type 'int *' with an rvalue of type 'void *'. So typecast the void pointer before assign it like this

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

提交回复
热议问题