C:无法使用void *类型的右值初始化变量 [英] C: Cannot initialize variable with an rvalue of type void*
本文介绍了C:无法使用void *类型的右值初始化变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下代码:
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 *'`.
谢谢.
推荐答案
编译器的错误消息非常清晰.
The compiler's error message is very clear.
calloc
的返回值为void*
.您正在将其分配给类型为int*
的变量.
The return value of calloc
is void*
. You are assigning it to a variable of type int*
.
对于C程序来说可以,但是对于C ++程序则不能.
That is ok with a C program, but not with a C++ program.
您可以将该行更改为
int* numberArray = (int*)calloc(n, sizeof(int));
但是,更好的选择是使用new
运算符分配内存.毕竟,您正在使用C ++.
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];
这篇关于C:无法使用void *类型的右值初始化变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文