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

4

22

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.

Chittagong answered 15/6, 2014 at 8:10 Comment(5)
int *numberArray = (int*)calloc(n, sizeof(int)); It´s called casting.Enlarger
In C++, malloc and calloc require a type cast.Asiatic
Is there no documentation for calloc anymore?Ghirlandaio
Well, you can also use new if it is C++.Asiatic
@j809 I replace calloc with new, but now he say: Expected a typeChittagong
S
44

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];
Sapajou answered 15/6, 2014 at 8:18 Comment(0)
A
3
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];
Asiatic answered 15/6, 2014 at 8:20 Comment(0)
C
0

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));
Collenecollet answered 15/6, 2014 at 8:19 Comment(0)
C
0

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

Carbonous answered 15/6, 2014 at 8:20 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.