malloc-从void *到double *的无效转换 [英] malloc - invalid conversion from void* to double*
本文介绍了malloc-从void *到double *的无效转换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想编写一个使用指针创建双精度数组副本的函数. 到目前为止,这是我的代码:
I want to write a function that creates a copy of a double array using pointers. This is my code so far:
#include <stdio.h>
#include <stdlib.h>
double* copy (double *array, int size)
{
double *v=malloc(sizeof(double)*size);
for (int i=0; i<size; i++)
*(v+i)=*(array+i);
return v;
}
int main ()
{
//double array[];
int size;
printf ("size= "); scanf ("%i",&size);
double *array=malloc(sizeof(double)*size);
for (int i=0; i<size; i++)
scanf("%f",&array[i]);
copy(array,size);
free(array);
}
我有2个无法消除的编译错误.我得到
I have 2 compilation errors that I can't get rid of. I get
从void *到double *的无效转换
invalid conversion from void* to double*
当我尝试使用malloc分配内存但我不明白自己在做什么错时.
when I try to allocate memory using malloc but I can't understand what I'm doing wrong.
推荐答案
您正在使用C ++编译器.
You are using a C++ compiler.
double *array=malloc(sizeof(double)*size);
在C语言中有效.从任何对象指针类型到void *
都有隐式转换.
is valid in C. There is an implicit conversion from any object pointer type to void *
.
在C ++中,它是无效的,没有这种隐式转换,您需要进行强制转换:
In C++ it is not valid, there is no such implicit conversion, and you need a cast:
double *array= (double *) malloc(sizeof(double)*size);
这篇关于malloc-从void *到double *的无效转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文