19

我有以下代码:

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

而且我无法理解为什么会收到以下错误。

Cannot initialize a variable of type 'int *' with an rvalue of type 'void *'`.

谢谢你。

4

4 回答 4

36

编译器的错误信息非常清楚。

calloc的返回值为void*。您将其分配给类型的变量int*

这在 C 程序中可以,但在 C++ 程序中不行。

您可以将该行更改为

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

但是,更好的选择是使用new运算符来分配内存。毕竟,您使用的是 C++。

int* numberArray = new int[n];
于 2014-06-15T08:18:47.133 回答
2
void* calloc (size_t num, size_t size);

分配和零初始化数组。为 num 个元素的数组分配一块内存,每个元素的长度为 size 个字节,并将其所有位初始化为零。有效结果是分配一个 (num*size) 字节的零初始化内存块。

成功时,指向函数分配的内存块的指针。此指针的类型始终为 void*,可以将其强制转换为所需的数据指针类型,以便可取消引用。如果函数未能分配请求的内存块,则返回空指针。

总而言之,由于在内存分配成功时calloc返回一个void*(通用指针),因此您必须在 C++ 中像这样对它进行类型转换:

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

如果是 C,你仍然可以跳过这个演员表。

或者,new用作:

int *numberArray = new int [n];
于 2014-06-15T08:20:34.740 回答
0

您在 C++ 代码中使用 C 内存重新分配样式。你想用的是newC++

所以你的代码将变成:

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

或者,您可以切换回 C 并将 calloc 与强制转换一起使用。

int* numberArray = (int*)calloc(n, sizeof(int));
于 2014-06-15T08:19:44.703 回答
0

calloc 的语法是:

void* calloc (size_t num, size_t 大小);

calloc 返回 void 指针。在您的代码中,您试图将 void 指针分配给整数指针。因此,您将无法使用“void *”类型的右值初始化“int *”类型的变量。所以在像这样分配它之前对 void 指针进行类型转换

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

于 2014-06-15T08:20:42.570 回答