C语言 malloc - 从 void* 到 double* 的无效转换

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30088025/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 11:55:15  来源:igfitidea点击:

malloc - invalid conversion from void* to double*

cmalloc

提问by Diana

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

I have 2 compilation errors that I can't get rid of. I get

我有 2 个无法消除的编译错误。我得到

invalid conversion from void* to double*

从 void* 到 double* 的无效转换

when I try to allocate memory using malloc but I can't understand what I'm doing wrong.

当我尝试使用 malloc 分配内存但我不明白我做错了什么。

回答by ouah

You are using a C++ compiler.

您正在使用 C++ 编译器。

double *array=malloc(sizeof(double)*size);

is valid in C. There is an implicit conversion from any object pointer type to void *.

在 C 中有效。存在从任何对象指针类型到 的隐式转换void *

In C++ it is not valid, there is no such implicit conversion, and you need a cast:

在 C++ 中它是无效的,没有这样的隐式转换,你需要一个强制转换:

double *array= (double *) malloc(sizeof(double)*size);

回答by Iharob Al Asimi

You are compiling c code, with a c++ compiler.

您正在使用 c++ 编译器编译 c 代码。

When you are using a c++ compiler, you should write c++ code, so malloc()is not so common in c++, instead

当您使用 c++ 编译器时,您应该编写 c++ 代码,因此malloc()在 c++ 中并不常见,而是

double *data = new double[size];

would be good c++ code, if you need to free()the pointer, you need to

将是好的 C++ 代码,如果你需要free()指针,你需要

delete[] data;

You can of course use malloc()in c++, but it would be like this

你当然可以malloc()在 c++ 中使用,但它会是这样的

double *data = static_cast<double *>(malloc(size * sizeof(double));

because void *in c++ is not converted to any pointer type automatically.

因为void *在 c++ 中不会自动转换为任何指针类型。

In c, however, there is no need for the cast, and in fact it makes the code unnecessarily ugly apart from hiding bugs from your program, cehck here Do I cast the result of malloc?.

但是,在 c 中,不需要强制转换,实际上除了隐藏程序中的错误之外,它使代码变得不必要地丑陋,请在这里检查我是否对 malloc 的结果进行了转换?.