【问题标题】:invalid conversion from *void to *int [-fpermissive] using malloc(sizeof())使用 malloc(sizeof()) 从 *void 到 *int [-fpermissive] 的无效转换
【发布时间】:2016-03-21 01:41:12
【问题描述】:

我正在编写一个计算两个数字的最大公分母的程序,但我遇到了malloc 函数和指针的问题。实际上很清楚堆栈和堆段如何在内存中工作以及为什么。但是,我还不能理解在程序中声明指针和使用malloc 是否具有功能,是否有必要。这是代码:

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

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

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

【问题讨论】:

  • 只有在将代码编译为 C++ 时才会收到此警告。 C 编译器不会给出这个警告。
  • @kaylum - #include &lt;iostream&gt; 我想说的另一个赠品。
  • @DanAllen 是的,你是对的。我错过了,只看到了C 标签。 @Ghislo 请修复您的标签,因为您似乎正在编写 C++ 代码而不是 C 代码(如果这确实是您的意图)。
  • #include &lt;iostream&gt;删除此行。
  • 您已标记问题 C,但使用了几个 C++ 结构。您需要决定您是在尝试编写 C 程序还是 C++ 程序。两者在这方面的建议完全不同。

标签: c pointers malloc heap-memory


【解决方案1】:

你需要投射:

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

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

请注意,这种转换在 C 中不是必需的,在 C 中可能需要 dangerous

除了#include &lt;iostream&gt;,您的代码中没有任何内容是 C++。所以删除它并用 C 编译器编译它,你就不需要这个演员表了。

【讨论】:

  • 既然是C++,不如使用static_cast&lt;&gt;,这样更难误认为C,如果代码被复制粘贴到实际的C源代码中,会提醒程序员删除强制转换。或者更好的是,在 C++ 中完全删除 malloc,使用 std::vector 代替。
  • @Medinoc 是的,我同意你的建议。但我不确定它是否真的是 C++。我想将标签编辑为 C++。但它实际上似乎是 C 代码,但包含 &lt;iostream&gt; 除外(因此 OP 将其编译为 C++)。
  • 您不应该在 C++ 程序中使用 malloc,因此无需首先考虑演员表。混合 malloc/free 而 C++ 中的其他所有内容都使用不兼容的new/delete,这是一个非常愚蠢的想法,只会导致错误。
  • OP删除了C++标签,没有代码建议使用C++,但是C。我认为唯一的问题是编译器,他使用了C++ 编译器。
  • @Lundin 请记住,如果您看不到匹配的 free() 替换为 delete[],请不要将 malloc() 替换为 new[](在这里,我们可以看到main函数中的free())。
猜你喜欢
  • 2016-06-06
  • 1970-01-01
  • 2013-08-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-11-11
  • 2019-09-22
相关资源
最近更新 更多