使用malloc(sizeof())从* void到* int [-fpermissive]的无效转换 [英] invalid conversion from *void to *int [-fpermissive] using malloc(sizeof())

查看:159
本文介绍了使用malloc(sizeof())从* void到* int [-fpermissive]的无效转换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个程序,该程序计算两个数字的最大公分母,但是我遇到了malloc函数和指针的问题.实际上,很明显堆栈和堆段在内存中的工作方式以及原因.但是,我还无法理解在程序中何时声明指针并使用malloc是否起作用,是否必要.这是代码:

I'm writing a program that calculates the greatest common denominator of two numbers, but i'm getting problem with malloc function and pointers. Actually it's clear how the stack and the heap segments work in the memory and why. But yet i'm not yet able to understand when declaring a pointer and using malloc is functional or not, is necessary or not, in a program. here is the code :

#include <iostream>
#include <stdlib.h>
#include <stdio.h>

int *calcolaDivisori(int);

int main(int argc, char** argv) {

    int foundCounter = 0;
    int i,j,s1,s2;
    int n1,n2;
    int mcd = 1,mcm;
    int *pn1,*pn2;
    int d1[100],d2[100];

    // INPUT dei due interi

    printf("Inserisci il primo numero :");
    scanf(" %d", &n1);
    printf("\nInserisci il secondo numero :");
    scanf(" %d", &n2);

    // calcolo divisori del primo e del secondo numero e li assegno ai relativi array

    pn1 = calcolaDivisori(n1);
    if (!pn1) return 1;
    pn2 = calcolaDivisori(n2);
    if (!pn2) return 1;

    for (i=0;i<n1;i++) {
        d1[i] = pn1[i];
    }

    for (i=0;i<n2;i++) {
        d2[i] = pn2[i];
    }

    free(pn1);
    free(pn2);

    // confronto i divisori e calcolo il MCD

    s1 = sizeof(d1) / sizeof(int);
    s2 = sizeof(d2) / sizeof(int);

    for(i=0; i<s1; i++) {
        for (j=foundCounter; j<s2;j++) {
            if (d1[i] == d2[j]) {
                mcd*= d1[1];
                foundCounter = j+1;
                break;
            }
        }
    }

    printf("\n\nIl minimo comune divisore e' : %d", mcd);

    return 0;
}

int *calcolaDivisori(int num) {
    int i;
    int *a = malloc(num * sizeof(int));
    if (!a) return NULL;
    for (i=2;i<num;i++) {
        if (num%i == 0) {
            num/=i;
            a[i-2]=i;
        }
    }

    return a;
}

运行命令时,标题出现错误:

I get the error in the title when is run the command :

int *a = malloc(sizeof(int));

推荐答案

您需要投射:

int *a = (int*)malloc(num * sizeof(int));

因为在C ++中没有从void*type *的隐式转换.

Because there's no implicit conversion from void* to type * in C++.

请注意,此强制转换在C语言中不是必需的,并且可能危险在C中也是如此.

Note that this cast is not required in C and could potentially be dangerous to do so in C.

除了#include <iostream>,您的代码中没有任何东西是C ++.因此,将其删除并使用C编译器进行编译,您将不需要此强制转换.

Except for #include <iostream>, nothing in your code is C++. So remove it and compile it with a C compiler and you wouldn't need this cast.

这篇关于使用malloc(sizeof())从* void到* int [-fpermissive]的无效转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆