[英]invalid cast from type 'void*' to type 'int*'
补充2 :更改为static
,它可以在Windows上的ubuntu上的bash中的gcc 4.8.4(ubuntu 4.8.4-2ubuntu1〜14 .04.3)中正常工作。 但是在使用gcc 4.9.2(tdm-1)的Windows10中它不能工作。 我将编译器更改为cygwin,它具有gcc 4.9.2,而不是tdm-1版本。 很奇怪,它有效! 所以我认为编译器也有一些错误!
1 :很抱歉我发现我的编译器不是gcc还是g ++,我是程序领域的新手,请原谅。 我用.c
来构建,但是它有一些我无法处理的内存泄漏错误。 因此,我更改为.cpp
进行构建,并且出现了这些错误。 这就是我的情况。
Windows 10的椭圆GCC 4.8.4 。 我使用C语言。
elipse给我一个错误: 从类型'void *'强制转换为类型'int *'[-fpermissive] 。
椭圆提示这些行有错误
FullList = malloc(N * sizeof(int));
l = malloc(N * sizeof(int));
我不知道该如何纠正。 任何线索将不胜感激!
这是涉及这句话的功能。
#define ALLCHK(x) if (x == NULL) {printf ("allocation error\n"); assert(x);}
void Generate_Permutation(int N, int *p)
/* generate permutation of length N in p */
/* p is zero based, but the permutation is not */
{
int i,j; /* to loop */
int lspot; /* offset in l */
int *FullList; /* unpermuted */
int *l; /* left to be used */
FullList = malloc(N * sizeof(int));
ALLCHK(FullList)
for (i=0; i<N; i++) *(FullList+i) = i+1;
l = malloc(N * sizeof(int));
ALLCHK(l)
memcpy(l, FullList, sizeof(int)*N);
for (i=0; i < N; i++) {
lspot = (int)(URan(&seed) * (N - i));
*(p+i) = *(l+lspot);
for (j=lspot; j<N-i; j++) *(l+j) = *(l+j+1);
}
free(l); free(FullList);
}
在C ++中, void*
不能隐式转换为int*
。 您需要显式转换malloc的结果:
fullList = static_cast<int*>(malloc(N * sizeof(int)));
l = static_cast<int*>(malloc(N * sizeof(int)));
由于您使用的是C ++,因此最好使用new
运算符:
fullList = new int[N];
l = new int[N];
// some code...
delete[] fullList;
delete[] l;
在进行此操作时,您可以使用唯一的指针:
std::unique_ptr<int[]> fullList = new int[N];
std::unique_ptr<int[]> l = new int[N];
// no delete at the end of the scope
但更简单的是,只需使用向量:
std::vector<int> fullList(N);
std::vector<int> l(N);
对我来说,似乎您正在将C代码片段移植到C ++(包括在C ++项目中?)。
将此答案视为解决问题的快速解决方案,而不是最佳解决方案。
在C ++中使用malloc
/ free
时,必须将malloc
返回的void*
指针转换为所需的指针类型:
FullList = static_cast<int*>(malloc(N * sizeof(int)));
l = static_cast<int*>(malloc(N * sizeof(int)));
这样做的原因(当简单地复制C代码时)是因为在C中,这些强制转换可以隐式执行。
其他选择是使用C编译器编译该文件,对于该文件,只需将文件重命名为.c
而不是.cpp
扩展名就足够了。 然后,g ++(C ++编译器)将自动使用gcc(C编译器)来编译代码。
同样,另一个选择是使用new
/ delete
而不是malloc
/ free
将其重写为“真实的” C ++代码,但是同样可以将其重写为使用现代内存管理(例如std :: vectors等)。
在C语言中,您不必强制转换(void *)malloc的结果。 在C ++中,除非您强制转换,否则编译器会哭。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.